我正在编写 Greasemonkey 脚本。我需要做的是在调用函数之前执行脚本,或者在函数开头执行脚本。
问题在于该函数位于文档中而不是 Greasemonkey 文件内。这就像覆盖函数,但不覆盖它,因为它必须在脚本完成后执行。
这是我完整的 Greasemonkey 代码,我不知道我错过了什么:
<pre>// ==UserScript==
// @name appname
// @version 1.0.0
// @author me
// @description blah
// @include http://www.runhere.net/*
// @exclude http://www.notinhere.com/*
// @run-at document-end
// ==/UserScript==
function addJQuery(callback) {
var script = document.createElement("script");
script.setAttribute("src", "http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js");
script.addEventListener('load', function() {
var script = document.createElement("script");
script.textContent = "(" + callback.toString() + ")();";
document.body.appendChild(script);
}, false);
document.body.appendChild(script);
}
function main() {
var originalFunction = unsafeWindow.add_comment;
unsafeWindow.add_comment = function(go_last_page) {
alert("if it is shown, then works!");
originalFunction.apply(unsafeWindow, new Array(true));
}
}
//Load JQuery and execute function
addJQuery(main);</pre>
我需要调用的函数位于页面中,名为add_comment
。它有一个 bool 类型的参数。我不熟悉 javascript,但我需要做这个简单的扩展。
我将非常感谢你的帮助。
最佳答案
用调用您的函数然后调用原始函数的包装函数替换该函数。
var originalFunction = someObject.someFunction;
someObject.someFunction = function() {
executeMyScript();
return originalFunction.apply(someObject, arguments);
}
关于javascript - 在调用函数之前执行 Greasemonkey 脚本中的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9572410/