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

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

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

相关标签:
3条回答
  • 2020-11-29 09:55

    Thank you. That helped. However, I realized I needed to do this to get it to work

    location.href="javascript: window.alert = function(x) {console.log(x)};"
    

    if I wanted to remove alerts and confirms, I can do

    location.href="javascript: window.alert = function(x) {console.log(x)}; window.confirm = function(){return true;};";
    
    0 讨论(0)
  • 2020-11-29 10:00

    Yes you can, alert() is just a JavaScript method, you can override its functionality by doing.

    window.alert = function alert(msg) {
      console.log('Hidden Alert ' + msg);
    };
    

    Just remember to run that content script at document_start within the manifest via run_at manifest content script modifier.

    I believe there is an extension that just does that. The developer names it Nice Alert. https://chrome.google.com/extensions/detail/ehnbelnegmgdnjaghgomaakjcmpcakhk

    0 讨论(0)
  • 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);
    
    0 讨论(0)
提交回复
热议问题