igorpavlov
igorpavlov

Reputation: 3626

Prevent JavaScript event which is bound to an object to be overridden

I do:

// Can be edited
window.onbeforeunload = function(){
    console.log("A")
}

And then:

// Cannot be edited (for example, this code appears in 3rd party library)
window.onbeforeunload = function(){
    console.log("B")
}

Then I refresh a page and see "B" in console log. Expected. But I want to prevent the second bind to actually happen. Basically, I want to lock an event and prevent it from being overridden forever (during page life). As a result, I want to see "A" in console log on page refresh.

Note 1: I cannot edit a part of the code with console.log("B") as it may appear in third party JS library.

Note 2: Cross-browser solution needed.

Upvotes: 3

Views: 218

Answers (2)

Andreas Argelius
Andreas Argelius

Reputation: 3614

This seems to work:

window.onbeforeunload = function() { return "HI!"; };

Object.defineProperty(window, 'onbeforeunload', {
  writable: false
});

window.onbeforeunload = function() { return "BYE!"; };

Upvotes: 4

Jivings
Jivings

Reputation: 23260

It's not possible to seal window properties like you're asking.

However, if you change your code to use window.addEventListener() then you can stop the event from propagating to other event listeners:

window.addEventListener('beforeunload', function (e) {
    e.stopImmediatePropagation();
    console.log('A')
});

window.addEventListener('beforeunload', function (e) {
    e.stopImmediatePropagation();
    console.log('B')
});

A will be printed to the console on unload.

http://jsfiddle.net/voqb78hp/4/

Upvotes: 3

Related Questions