1

Here is what I'm trying to solve: I never want to be asked again if I really want to close a window. Unfortunately, some people think it's a good idea to add an alert() in onbeforeunload (or similar functions) to make their page stay longer on the screen.

Is it possible, permanently and for everything, to prevent onbeforeunload from begin redefined ?

For example, inside a Safari extension, is it possible to catch a modification made to onbeforeunload and prevent it ?

user3585425
  • 171
  • 9
  • Could you post the code you've tried? Are you requesting to block these popups, *outside of your code*, on other webpages? – Jimmy Smith May 27 '14 at 18:56
  • I'm not trying to block them, I'm trying to prevent any Javascript code to assign onbeforeunload, or at least a method to detect that it has been assigned and react. I have no code right now, I'm looking for the different methods to do it. – user3585425 May 27 '14 at 19:07
  • Unfortunately, that would be a "too broad" question. You're expected to ask here about concrete implementation problems after having tried to do so. – Xan May 27 '14 at 19:49
  • I understand you're new, but here's a good [blog](http://blog.stackoverflow.com/2010/11/qa-is-hard-lets-go-shopping/) to check out. Here's a [question](http://stackoverflow.com/questions/4395525/safari-extension-beforeload-event-documentation) that may help get you started. – Jimmy Smith May 27 '14 at 20:12

1 Answers1

1

It looks like it is possible using Object.defineProperty. You need to manage to execute the following code in the execution context of all webpages where you want to block that property:

Object.defineProperty(window, 'onbeforeunload', {value: null});

In a Chrome extension you can achieve that using a content script that runs in <all_urls> and all_frames at document_start, and using some of the techniques described in this answer to make the code run in the execution context of the page. For a Safari extension it should be more or less the same.

Note that a page could still register a beforeunload handler using window.addEventListener. To prevent that from happening you could add to the previous line of code something like:

(function() {
    var prevFunc = window.addEventListener;
    window.addEventListener = function( name ) { 
        if( name !== 'beforeunload' )
            return prevFunc.apply(window, arguments);
    }
})();
Community
  • 1
  • 1
rsanchez
  • 14,467
  • 1
  • 35
  • 46