Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"delete" - restore native function not working for changed prototype, how then?

if you change native function like this:

window.open= function (a,b,c)
{
    alert(2);
}

then later you can just

delete window.open

and it would restore original function, BUT:

if you change its prototype like this:

window.__proto__.open= function (a,b,c)
{
    alert(3);
}

then delete won't do anything =\ any ideas how to restore it now?

like image 897
Owyn Avatar asked Jan 16 '14 10:01

Owyn


2 Answers

When you change window.open to something else, e.g. using window.open = 'something else';, then you're shadowing the open method from the prototype;

// Looking up window.open (in the prototype chain)....
window.open;           // Found, result == 'something else'
window.__proto__.open; // Not accessible any more (shadowed by previous line)

After invoking delete window.open to delete 'something else', the original method becomes visible again, because it had never disappeared from the prototype chain.

But if you've modified the open method on the prototype, e.g. window.__proto__.open = bogus;, then you cannot easily restore the old method. So, to get the "open window" behavior again, you need to either keep a reference to the original method before replacing it,

var original_open = window.open;
window.__proto__.open = 'bogus';
// .... whatever ....
// Now restore it:
window.__proto__.open = original_open;

Or borrow it from another window, e.g. using a temporary new frame:

var frame = document.createElement('iframe');
document.body.appendChild(frame);
window.__proto__.open = frame.contentWindow.open;
frame.parentNode.removeChild(frame);

This whole idea is ridiculous though: You should not break built-in methods.

like image 107
Rob W Avatar answered Oct 14 '22 12:10

Rob W


delete window.open;

(function(func) {
    var frame = document.createElement('iframe');
    document.body.appendChild(frame);
    // Intentionally set in global scope
    window[func] = frame.contentWindow[func];
    frame.parentNode.removeChild(frame);
})("open");

open

ƒ open() { [native code] }

like image 35
Zibri Avatar answered Oct 14 '22 12:10

Zibri