Skip to content Skip to sidebar Skip to footer

Restore Native Window Method

For a script I'm writing, I'd like to use the native window.open method. However, a script already loaded to which I don't have access, overwrites the global window.open method wit

Solution 1:

I've found this question and the accepted answer (using an iframe) could be used in your case.

The only issue is you can only use the retrieved version of window.open as long as the iframe is still in your document.

function customOpen() {
    // local variables definitions : 
    var url = "https://stackoverflow.com", iframe, _window;

    // creating an iframe and getting its version of window.open : 
    iframe = document.createElement("iframe");
    document.documentElement.appendChild(iframe);
    _window = iframe.contentWindow;

    // storing it in our window object
    window.nativeOpen = _window.open;   

    try {
        window.open(url);
    } catch (e) {
        console.warn(e); // checking that window.open is still broken 
    }
    window.nativeOpen(url);

    // deleting the iframe : 
    document.documentElement.removeChild(iframe);
}

document.getElementById("button").addEventListener("click", customOpen);

Another JSFiddle


Keeping the workaround answer in case someone needs it :

Can you execute a custom script prior to the execution of the script that redefines window.open? If so, you could create a copy of the window.open in another global variable.

It could look like this :

1. First : a backup script

window.nativeOpen = window.open;

2. Then, whatever the window.open overwriting script does :

window.open = false; // who does that, seriously?

3. Your window opening script, that'll use your window.open copy :

function customOpen() {
    var url = "https://stackoverflow.com";
    try {
        window.open(url);
    } catch (e) {
        console.warn(e);
    }
    window.nativeOpen(url);
}

JSFiddle example


Post a Comment for "Restore Native Window Method"