簡體   English   中英

退出瀏覽器並關閉選項卡時發出警報

[英]Alert on exit the browser and closing the tab

我嘗試了onbeforeunload,因為它需要一次用戶交互才能調用,有沒有辦法在沒有用戶交互的情況下調用事件,因為用戶在打開應用程序選項卡后退出瀏覽器。 或任何其他不使用 onbeforeunload 的解決方案來阻止用戶退出瀏覽器。

window.onbeforeunload = function (event) {
    var message = 'Important: Please click on \'Save\' button to leave this page.';
    if (typeof event == 'undefined') {
        event = window.event;
    }
    if (event) {
        event.returnValue = message;
    }
    return message;
};

        $(document).ready(function(){ 
            $(".label").click(function(){
            alert('label');
            window.onbeforeunload = null;
            }
            ); 
             $(".new_cont").click(function(){
            alert('new_cont');
            window.onbeforeunload = null;
            }
            );
        })

在 FireFox 和 Chrome 中,您至少需要與頁面進行一次交互。 由於此功能是為了避免丟失用戶輸入的數據,因此如果頁面上沒有發生任何操作,則用戶沒有輸入任何數據。

這是因為 onbeforeunload 附加到 window object,並且當您卸載主頁時,除非您關注此 iframe,否則不會觸發此事件。

 <script type="text/javascript">
 window.onbeforeunload = function () {
     return "Did you save your stuff?"
 }

供參考https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload

暫無
暫無

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

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