delphirules
delphirules

Reputation: 7448

How to really disable beforeunload?

A lot of web pages try to make you don't exit them by using the beforeUnload event on JS. Facebook, for instance, will show a warning if you try to use back / forward button , as the image below shows :

enter image description here

To avoid this i always used the code below to 'unbind' the event :

window.onbeforeunload = null;

But this is not working anymore. Even after running the code below, the warning message will still shows if i try to leave the page.

How to really get rid of these messages in a web application ? Facebook is only an example, i'm trying to do this using JS for study purposes.

Upvotes: 1

Views: 1121

Answers (1)

Jacob
Jacob

Reputation: 1835

The event is probably being registered via addEventListener rather than onbeforeunload. You could try adding a new event listener that overrides the previous one.

window.addEventListener("beforeunload", (event) => {
    event.stopImmediatePropagation();
}, true);

The third parameter being true causes the event to go all the way down, so any other listeners will be prevented.

Upvotes: 1

Related Questions