How to completely disable all exit warning/confirm messages with userscript?

烂漫一生 提交于 2019-12-05 11:36:53

I assume you're using some older version of Chrome, because this behavior has been removed since Chrome 51 [Custom messages in onbeforeunload dialogs (removed)].

The problem relies on onBeforeUnload event. Browsers (Chrome and Firefox at least) have disabled messages from inside onUnload event. The pages you're trying to hook your timer and change the window.onbeforeunload = null are probably also using a timer to set the same event with a very small interval value, even 1 millisecond, so it will be really difficult to override that event when having an other timer with a smaller interval setting it again and again. My approach is to kill all the timers inside the script and it worked for me with Chrome 49 I have in an old VM.

// ==/UserScript==

(function() {
    'use strict';

    var killId = setTimeout(function() {
        for(var i = killId; i > 0; i--) clearInterval(i);
        window.onbeforeunload = null;
        // If you don't use interval timers then disable setInterval function
        // else you can store the function to a variable before
        // you set it to an empty function;
        // Same goes for setTimeout
        setInterval = function() {};
    }, 10);

})();

For a refference test page, I used this simple javascript that runs an interval timer to set the window.onbeforeunload every millisecond:

function goodbye(e) {
    var msg = 'You sure you want to leave?';
    if(!e) e = window.event;
    if(e) {
        //e.cancelBubble is supported by IE - this will kill the bubbling process.
        e.cancelBubble = true;
        e.returnValue = msg; //This is displayed on the dialog

        //e.stopPropagation works in Firefox.
        if (e.stopPropagation) {
            e.stopPropagation();
            e.preventDefault();
        }
    } else
        return msg;
}

// Set a timer to hook `onBeforeUnload` event every millisecond
setInterval(function() { window.onbeforeunload = goodbye; }, 1);

Some pages may use setTimeout() instead setInterval() so you may want to also disable setTimeout = function() {} function.

Try Object.defineProperty

Object.defineProperty(window, 'onunload', { 
    value: null,
    configurable: false
});

window.onunload = 1;

window.onunload;
// null

configurable is set to false which means the property can't be changed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!