Skip to content Skip to sidebar Skip to footer

Assuming I Deleted Window.alert, How Would I Get It Back?

Assume I do this in javascript delete window.alert; // returns true then the output of console.log(window.alert); will be 'undefined' There must be a way for code to access the na

Solution 1:

Even though the other answers provoke the impression "there is no getting back deleted objects of window in javascript", as for with my question that was the function of window.alert, there is actually a way without prior backup/copy to get back deleted properties of the global window object.

get a "virgin" window via injecting an iframe into the DOM

While window.alert is gone for window we can get ut back by creating another window, or more precisely contentWindow via an iframe we inject into the DOM.

// step 1 "delete window.alert and check its gone, no backupcopy"console.log(typeofwindow.alert); // "function"deletewindow.alert;
console.log(typeofwindow.alert); // "undefined"try{ window.alert(1); } catch(e){console.log(e);} // TypeError: "window.alert is not a function"// step 2 "insert an iframe into DOM, to take window.alert from its contentWindow"var iframe = document.createElement("iframe");
document.body.appendChild(iframe);
window.alert = iframe.contentWindow.alert;
console.log(typeofwindow.alert); // "function"

impact and consequences

It would seem highly interesting, as a way of a fine-grained disabling of access to certain Javascript and DOM functionality, to simply delete/overwrite those properties. Some form of "prevent scripts from showing an alert popup" via window.alert=function(){}. This appealing idea was also some of the motivation to my question. As it rests now, it seems this is not easily possible unless we prevent the loopwhole to regain a "pristine" unmotivied copy of window via iframe.contentWindow.

The "undelete-via-iframe" trick is based on https://getfastvpn.com/webrtc-leak-test.html, which applied the iframe-regain trick to prevent webrtc functionality removal done "naively" via browser addons

Solution 2:

The window object is a normal JavaScript object. You can simply "save" the alert function by keeping a reference to it.

const alert = window.alert;
deletewindow.alert; // window.alert is now undefinedwindow.alert = alert;

Solution 3:

How do you 'undelete' window.alert?

You would have needed to save a reference of the function:

var windowAlertBackup = window.alert;

And then:

window.alert = windowAlertBackup;

What is actually happening?

Any native window function is actually implemented by the javascript interpreter. In javascript window.alert is a pointer to that native function. window.alert is the only default reference to the native window.alert code.

Post a Comment for "Assuming I Deleted Window.alert, How Would I Get It Back?"