Update: For modern versions of Tampermonkey, Violentmonkey, Greasemonkey (but strongly recommended to avoid GM 4+):
You can intercept alert()
in most cases by using @run-at document-start
. For example, load this script and then visit the test page http://output.jsbin.com/ajeqe4/6:
// ==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);
};
请注意,如果您是运行篡改猴, 你可以通过切换到更有效地阻止警报Inject Mode: Instant
:
篡改猴设置 => 配置模式: Advanced
=> 实验性的 => 注入模式: Instant
.
如果您的脚本需要 GM_ 函数,它必须设置@grant
除了没有之外。在这种情况下使用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 .
检查代码(http://jsbin.com/ajeqe4/6/edit http://jsbin.com/ajeqe4/6/edit),您将看到 3 个警报。 Greasemonkey 只能阻止正在触发的警报load
(通常)。
其他因素可能会阻止 GM 停止警报的能力...页面加载速度太快或可能关闭。
将该页面的源代码粘贴到pastebin.com,尽可能不进行编辑。也许您还可以做其他事情。也许通过 adblock 阻止脚本?
否则,您将不得不编写扩展/附加组件。