2012-03-05 189 views
0

我正在使用Greasemonkey脚本。我需要做的是在函数被调用之前执行脚本,或者在函数的开头执行脚本。在调用函数之前执行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功能。它有一个布尔类型的参数。我不熟悉JavaScript,但我需要做这个简单的扩展。

我真的很感谢你的帮助。

+0

是否'alert'节目?你可以用'arguments'替换'new Array(true)'。 – 2012-03-05 22:48:43

回答

0

您可以将该函数保存到一个变量,然后覆盖函数。

例子:

var _func = functionIWant; 
functionIWant = function(){ 
    // Do whatever 
    _func(); // Call original function 
} 
+0

我已添加扩展程序源代码。我无法让它工作。 此致敬礼。 @GGG – user1250538 2012-03-05 19:37:51

2

替换调用你的函数,然后将原来函数的包装函数的函数。

var originalFunction = someObject.someFunction; 

someObject.someFunction = function() { 

    executeMyScript(); 
    return originalFunction.apply(someObject, arguments); 

} 
0

该代码经由addJQuery()法注入main()到目标页。这意味着使用unsafeWindow是不恰当的 - 这将是未定义的。

另外,在这种情况下,您可能不需要使用.apply()。最后,代码使用了一个变量,即go_last_page,似乎并没有在任何地方定义。

因此,代码是:

function main() { 
    var originalFunction = add_comment; 
    add_comment    = function (/*go_last_page*/) { 
     alert ("if it is shown, then works!"); 
     /* This next line is probably not needed. "this" and "arguments" are 
      special JS variables. 
     originalFunction.apply (this, arguments); 
     */ 
     originalFunction (true); //-- Simplified call is probably sufficient. 
    } 
} 
相关问题