现场有类似的代码(其站点位于 LAN 上)
<script language="JavaScript" type="text/javascript">
alert("ble");
</script>
我尝试使用 GM 禁用该警报。我正在尝试这样做
unsafeWindow.alert=function() {};
但我看到警报并收到此错误
Error: uncaught exception: [Exception... "Component is not available" nsresult: "0x80040111 (NS_ERROR_NOT_AVAILABLE)" location: "JS frame :: file:///C:/Documents%20and%20Settings/arokitnicki/Dane%20aplikacji/Mozilla/Firefox/Profiles/sm4bsods.default/extensions/%7Be4a8a97b-f2ed-450b-b12d-ee082ba24781%7D/components/greasemonkey.js :: anonymous :: line 377" data: no]
如何禁用该警报?
附注这不是一个 javascript 问题,而是一个 Greasemonkey 问题。
编辑:
它的公司网站,所以我无法粘贴真实的代码
<head>
<script>
dojo.require("dojo.back");
dojo.back.init();
</script>
</head>
<body onload="someMethod()">
<iframe></iframe>
<script>
alert("bla");
</script>
</body>
标题中还有一些脚本和 CSS 声明。
最佳答案
更新:对于 Tampermonkey、Violentmonkey、Greasemonkey 的现代版本(但强烈建议避免使用 GM 4+):
在大多数情况下,您可以使用 @run-at document-start
拦截 alert()
。例如,加载此脚本,然后访问the test page :
// ==UserScript==
// @name _Overwrite Alert
// @match *://output.jsbin.com/*
// @grant none
// @run-at document-start
// ==/UserScript==
var alrtScope;
if (typeof unsafeWindow === "undefined") {
alrtScope = window;
} else {
alrtScope = unsafeWindow;
}
alrtScope.alert = function (str) {
console.log ("Greasemonkey intercepted alert: ", str);
};
<小时/>
请注意,如果您运行 Tampermonkey,您可以通过切换到注入(inject)模式:即时
来更有效地阻止警报:
Tampermonkey 设置 => 配置模式: 高级
=> 实验 => 注入(inject)模式:> 即时
。
如果您的脚本需要 GM_ 函数,则必须将 @grant
设置为 none 以外的值。在这种情况下,请像这样使用 exportFunction()
:
// ==UserScript==
// @name _Overwrite Alert
// @match *://output.jsbin.com/*
// @grant GM_addStyle
// @run-at document-start
// ==/UserScript==
function myAlert (str) {
console.log ("Greasemonkey intercepted alert: ", str);
}
unsafeWindow.alert = exportFunction (myAlert, unsafeWindow);
<小时/>
<小时/>
旧答案,2011 年 8 月之前的 Greasemonkey:
unsafeWindow.alert=function() {};
在某些情况下工作正常。
但是,如果这确实是页面上的代码,那么您将无法使用 Greasemonkey 停止该警报。
这是因为该警报将在页面加载期间和 DOMContentLoaded
事件之前触发 - 这是 Greasemonkey 触发的时间。
加载此 GM 脚本:
// ==UserScript==
// @name Overwrite Alert
// @description Overwrites alert()
// @include http://jsbin.com/*
// ==/UserScript==
unsafeWindow.alert=function() {};
然后访问:http://jsbin.com/ajeqe4/6 .
检查代码 ( http://jsbin.com/ajeqe4/6/edit ),您将看到 3 个警报。 Greasemonkey 只能停止在加载
时触发的警报(通常)。
其他因素可能会阻止 GM 停止警报的能力...页面加载速度太快或可能关闭。
<小时/>将该页面的源代码粘贴到pastebin.com,尽可能不进行编辑。也许您还可以做其他事情。也许通过 adblock 阻止脚本?
否则,您将不得不编写扩展/附加组件。
关于javascript - 如何使用用户脚本覆盖警报功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47060420/