簡體   English   中英

在瀏覽器窗口/標簽關閉時打開自定義彈出窗口

[英]open a custom popup on browser window/tab close

我正在嘗試在瀏覽器窗口\/標簽關閉時打開一個自定義彈出窗口。

詳細地說,如果用戶單擊瀏覽器窗口\/選項卡關閉按鈕,則會出現一個帶有一些內容的自定義彈出窗口,或者可能有一些選項要求關閉或繼續頁面。

這是僅帶來默認警報彈出窗口的代碼:

window.onbeforeunload = function() {
              var message = 'Do you want to leave this page?';
              return message;
          }

 <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text\/html; charset=UTF-8" \/> <script src="https:\/\/code.jquery.com\/jquery-3.3.1.min.js"><\/script> <title>K3logics.com<\/title> <script> var mouseX = 0; var mouseY = 0; var popupCounter = 0; document.addEventListener("mousemove", function(e) { mouseX = e.clientX; mouseY = e.clientY; document.getElementById("coordinates").innerHTML = "<br \/>X: " + e.clientX + "px<br \/>Y: " + e.clientY + "px"; }); $(document).mouseleave(function () { if (mouseY < 100) { if (popupCounter < 1) { alert("Please do not close the tab!"); } popupCounter ++; } }); <\/script> <\/head> <body> <div id="page-wrap"> <span id="coordinates"><\/span> <h1>Hi, Move your mouse cursor around then try to close the window of browser! - <a href="https:\/\/www.k3logics.com" target="_blank">https:\/\/www.k3logics.com<\/a><\/h1> 
<\/body> <\/html><\/code><\/pre>

"

我也建議你不要這樣做,但是,你問了一個問題,應該得到一個答案。

更新 (2022)由於新的瀏覽器安全設置,此代碼不再有效。

 var popit = true; window.onbeforeunload = function() { if (popit == true) { popit = false; return "Are you sure you want to leave?"; } }

window.onbeforeunload = function (e) 
{
    e = e || window.event;

        e.returnValue = 'You want to leave ? ';


};

jsFiddle

您正在談論的功能是 window.onbeforeunload 事件,不幸的是,可以自定義它的唯一方法是為用戶提供自定義字符串消息,因為濫用的可能性非常高。

在 msdn 上為 Internet Explorer 提供的 api 參考說明:

The default statement that appears in the dialog box, "Are you sure you want to navigate away from this page? ... Press OK to continue, or Cancel to stay on the current page.", cannot be removed or altered.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM