2010-05-27 38 views
6

我需要一個消息腳本,它只會在人們離開當前網頁而不是當前網站時出現。外部鏈接所需的OnUnload消息

當人們完全離開網站時,消息會出現,他們需要按OK按鈕才能保持當前頁面(並取消離開網站)。

當人們實際停留在網站上或當他們點擊內部鏈接或頁面時,腳本可能無法運行。

可以這樣做嗎?

+0

PS我的網站http://www.consolepro.net這profides任天堂Wii的softmod軟MOD 確實有其生成的鏈接的全自動 – tumtummetjes 2010-05-27 13:43:34

+0

可能的複製腳本[離開網站時顯示警告,而不僅僅是頁面](http://stackoverflow.com/questions/2365994/display-a-warning-when-leaving-the-site-not-just-the-page) – KyleMit 2017-04-13 12:34:35

回答

5

結帳this very basic example solution。它設置onbeforeunload處理程序,但如果用戶單擊內部鏈接,則將其刪除。以下是示例解決方案代碼的通用版本。

HTML

<a href="internal_link.html">internal link</a> 
<a href="http://www.example.com">external link</a> 

JS(使用jQuery):

window.onbeforeunload = function(){ 
    return "Are you sure you want to leave our website?"; 
} 
$(function(){ 
    $('a, input, button').click(function(){ 
      window.onbeforeunload = null; 
    }); 
}); 
+0

那麼總代碼會包含查詢字符串等呢?我不明白內部鏈接的一部分?因爲我無法更改我們的內部鏈接,這些鏈接是由我們的購物車 – tumtummetjes 2010-05-28 00:18:02

+0

自動生成的,而且正在關閉HTML標記正文部分等。 – tumtummetjes 2010-05-28 00:18:53

+0

行'internal link'僅僅是一個鏈接的示例,它與「location.host」具有相同的域名。 。任何對你的網站「內部」的鏈接(意味着它不鏈接到不同的域)應該導致'if'語句'this.href.match(location.host)'返回'true',導致' onbeforeunload'處理程序將被刪除,從而防止出現「彈出消息」消息「您確定要離開我們的網站嗎?」消息。 [...繼續以下...] – Adam 2010-06-02 04:24:24

1

我有一個類似的問題。然而,在我的情況下,如果有人按F5或關閉窗口,此消息應該根據用戶的語言進行翻譯。

按照我的小例子。

<html> 
<head> 
<script type="text/javascript"> 
function closeThis() 
{ 
    if (window.confirm("Minha mensagem!")){ 
     window.close(); 
    } 
} 

function test() 
{ 
    // Add a warning in case anyone tries to navigate away or refresh the page 
    return confirm("Minha mensagem"); 
} 


</script> 
</head> 
<body onbeforeunload=test();> 
<p>Hello World! Press F5 or Close this Window</p> 
</body> 
</html> 
1

在大多數情況下,除了一個以外,您不需要彈出所有事件:用戶關閉窗口。

這裏是我的這個解決方案:

$(window).on('beforeunload', function() { 
    /* whatever you want here */ 
} 

$(document).on('click keydown', function(){ 
    $(window).off('beforeunload'); 
});