繁体   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