最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - prevent onbeforeunload to close page in any case - Stack Overflow

programmeradmin0浏览0评论

I want to prevent browser to close page in any case or in other case, Prevent browser to do anything when onbeforeunload is called. Here is my code which i have tried.

 (function() {
    var proxied = window.onbeforeunload;
    window.onbeforeunload = function(e) {
        e.preventDefault();
        e.stopPropagation();
            //i want to stop everything
        console.log('stay here');
        // return 'message';
    };
})();
  • I want to perform a action before leaving the page (disconnect the chat)

I want to prevent browser to close page in any case or in other case, Prevent browser to do anything when onbeforeunload is called. Here is my code which i have tried.

 (function() {
    var proxied = window.onbeforeunload;
    window.onbeforeunload = function(e) {
        e.preventDefault();
        e.stopPropagation();
            //i want to stop everything
        console.log('stay here');
        // return 'message';
    };
})();
  • I want to perform a action before leaving the page (disconnect the chat)
Share Improve this question edited Jun 11, 2015 at 12:47 asked Jun 11, 2015 at 12:39 user4069483user4069483 3
  • If you could prevent browsers from closing windows, I guess the internet would look very different. This is AFAIK. not possible – firelynx Commented Jun 11, 2015 at 12:42
  • is this a function call e.stopPropagation? because you are not () calling it – firelynx Commented Jun 11, 2015 at 12:45
  • Possible duplicate of Prevent a webpage from navigating away using JavaScript – georgeawg Commented Nov 4, 2019 at 20:35
Add a comment  | 

2 Answers 2

Reset to default 11

You can't outright prevent a user from leaving the page (This would lead to much abuse on spam/advertisement sites who try to get you to stay on a page), but you can show things such as a window which causes a confirm prompt to the user. Have a look at Prevent a webpage from navigating away using JavaScript which can lead you to the right direction of what you're trying to accomplish.

There is no way to stop browser to close. The browser doesn't allow you to do that.

发布评论

评论列表(0)

  1. 暂无评论