我可以使用 Google Chrome 扩展程序阻止 alert() [英] Can I prevent an alert() with a Google Chrome Extension

查看:86
本文介绍了我可以使用 Google Chrome 扩展程序阻止 alert()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以创建一个 Google chrome 扩展程序来防止页面执行 alert() 吗?

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

推荐答案

正如@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);

这篇关于我可以使用 Google Chrome 扩展程序阻止 alert()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆