Can I prevent an alert() with a Google Chrome Extension

后端 未结 3 486
礼貌的吻别
礼貌的吻别 2020-11-29 09:27

Can I create a Google chrome extension to prevent the page from doing an alert() ?

3条回答
  •  天命终不由人
    2020-11-29 10:09

    As @MrGlass said, currently, Chrome Extensions run in a separate environment, limiting access to the actual window object and providing a duplicate that is only valid for the extension.

    To solve this, we can inject a script element directly into the document. This way, you access the document's environment and the real window object.

    First, lets create the function (I added the "confirm" as well, because some confirms were annoying me so much):

    var disablerFunction = function () {
    
        window.alert = function alert(msg) { console.log('Hidden Alert ' + msg); };
        window.confirm = function confirm(msg) { 
            console.log("Hidden Confirm " + msg); 
            return true; /*simulates user clicking yes*/ 
        };
    
    };
    

    Now, what we're going to do is to transform that function in a text script and enclose it in parentheses (to avoid possible conflicts with actual vars in the page environment):

    var disablerCode = "(" + disablerFunction.toString() + ")();";
    

    And finally, we inject a script element, and immediately remove it:

    var disablerScriptElement = document.createElement('script');
    disablerScriptElement.textContent = disablerCode;
    
    document.documentElement.appendChild(disablerScriptElement);
    disablerScriptElement.parentNode.removeChild(disablerScriptElement);
    

提交回复
热议问题