且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我可以使用 Google Chrome 扩展程序阻止 alert()

更新时间:2023-10-28 18:33:34

正如@MrGlass 所说,目前,Chrome 扩展在单独的环境中运行,限制对实际 window 对象的访问并提供重复这仅对扩展有效.

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.

为了解决这个问题,我们可以直接在文档中注入一个脚本元素.这样,您就可以访问文档的环境和真正的 window 对象.

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);