Assume I do this in javascript
delete window.alert;
// returns true
then the output of console.log(window.alert);
will be \"
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.
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;
delete window.alert; // window.alert is now undefined
window.alert = alert;
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.
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(typeof window.alert); // "function"
delete window.alert;
console.log(typeof window.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(typeof window.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