Search code examples
javascriptfirefox-addononbeforeunload

Disabling beforeunload dialogues in Firefox 29 extension


I am attempting to disable beforeUnload dialogs in an extension for Firefox, which has worked up until FF28 by wrapping the window in an XPCNativeWrapper and redefining window.onbeforeunload using addeventlistener.

Example JavaScript:

var win = new XPCNativeWrapper(window, "onbeforeunload", "event", "addEventListener()");
var beforeUnload = win.onbeforeunload;
win.onbeforeunload = null;
var newBeforeUnload = function(e) {
    beforeUnload();
    //code to remove dialog
}
win.addEventListener('beforeunload', newBeforeUnload, false);

This has stopped working in FF29 when the beforeUnload method changes the location of a page. In FF29 I receive an error "Access to 'chrome://browser/content/page.html' from script denied".

Example of JS on page:

window.onbeforeunload = function() {
    parent.frame2.location="page.html";
};

Solution

  • So, I was able to resolve my issue using the following:

    windowToModify.location.replace("javascript:(" + function() {
        window.oldBeforeUnload = window.onbeforeunload;
        window.onbeforeunload = function(E) {
            window.oldBeforeUnload();
            var evt = e || window.event;
            if (evt && evt.returnValue) {
                delete evt['returnValue'];
            }
        };
        window.onunload = null;
    } + ")()");
    

    so, javascript:(/*some javascript as a string */) is a valid location and it will run in the scope of the window/frame. This script sets a property called window.oldBeforeUnload and then overrides onbeforeunload to disable the before unload dialogue.

    This should work in FF 3.6+