Assuming I deleted window.alert, how would I get it back?

前端 未结 3 1604
遇见更好的自我
遇见更好的自我 2021-01-27 01:51

Assume I do this in javascript

delete window.alert;
// returns true

then the output of console.log(window.alert); will be \"

相关标签:
3条回答
  • 2021-01-27 02:29

    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.

    0 讨论(0)
  • 2021-01-27 02:37

    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;
    
    0 讨论(0)
  • 2021-01-27 02:47

    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(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

    0 讨论(0)
提交回复
热议问题