网站上有这样的代码(它在局域网上的网站)
<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>
header中还有一些脚本和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 Mode: Instant
更有效地阻止警报:
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 只能停止在 load
时触发的警报(通常)。
其他因素可能会阻止 GM 停止警报的能力......页面加载速度过快或关闭。
在 pastebin.com 上粘贴该页面的源代码,如果可能的话,请未经编辑。您可能还有其他事情可以做。也许通过 adblock 阻止脚本?
否则,您将不得不编写一个扩展/附加组件。
关于javascript - 如何用用户脚本覆盖警报功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4656702/