2010-09-08 23 views
2

我有一个脚本,在FireFox中使用unsafeWindow,因为这没有奏效,我搜索了另一个选项,并发现它,我只是想知道:我怎样才能将我的脚本中的变量用于unsafeWindow解决方法?使用userscript中的变量在Google Chrome页面中注入JS?

我的代码是:

// ==UserScript== 
// @name Test 
// @description Test 
// @include http://www.google* 
// ==/UserScript== 

var toAlert = "This is what I want to alert..."; 
alert("Before implementation..."); 
contentEval(function(){ alert(toAlert);}); 
alert("And after..."); 
function contentEval(source) { 
    // Check for function input. 
    if ('function' == typeof source) { 
    // Execute this function with no arguments, by adding parentheses. 
    // One set around the function, required for valid syntax, and a 
    // second empty set calls the surrounded function. 
    source = '(' + source + ')();' 
    } 

    // Create a script node holding this source code. 
    var script = document.createElement('script'); 
    script.setAttribute("type", "application/javascript"); 
    script.textContent = source; 

    // Insert the script node into the page, so it will run, and immediately 
    // remove it to clean up. 
    document.body.appendChild(script); 
    document.body.removeChild(script); 
} 

而且它不工作... 我在做什么错?

+0

你正在追加脚本并立即删除它,我怀疑这可能是一个原因。 – Neutralizer 2010-09-09 14:59:10

+0

也请确定你的函数“contentEval”是否工作正常。 – Neutralizer 2010-09-09 15:00:00

回答

4

如果toAlert恰好在页面的全局范围内定义,那么您的脚本就可以工作。

在Chrome中,扩展/ Greasemonkey JavaScript不能与页面JavaScript共享变量或闭包。
这就是为什么你不能直接注入该函数,从扩展范围到页面范围,但必须从源字符串重新创建它。

这意味着,如果你在页面范围内创建一个函数,任何变量或函数,你的功能要求必须:

  1. 已经存在,全球范围内,在源页面。
  2. 也可以通过脚本进入源页面。

例如,修改你的代码是这样的...

//-- Must recreate the variable that the function requires. 
scriptStr = 'var toAlert="' + toAlert +'";'; 

//-- Now the function. 
scriptStr += '(' + source.toString() + ')();' 

var script = document.createElement('script'); 
script.textContent = scriptStr; 

...作品,但这种做法显然变得混乱。 (A)将所有JavaScript保留在扩展名中;不要与页面的JavaScript进行交互。 (B)如果您必须与页面的JS进行交互,或者像jQuery一样加载库,则将代码的所有放在一个main()函数中,并将其编写到源页面中。

像这样:

function localMain() 
{ 
    /*--- Put EVERYTHING inside this wrapper, functions and variables. 
     Call or use nothing else that's defined in the GM script here. 
     Can use objects in the source page's scope, though. 
    */ 
} 

//--- Now create the function in the page's scope and run it. 
var scriptNode   = document.createElement ("script"); 
scriptNode.textContent = localMain.toString() + "\n localMain();"; 
document.head.appendChild (scriptNode); 

请注意,如果您还装载库到页面的范围,那么你可能需要通过使用定时器并检查该库延迟运行localMain()

+0

谢谢,我已经使用了第一个选项,它工作的很棒! – ManIkWeet 2010-09-10 07:10:29

+0

不客气。乐意效劳。 – 2010-09-10 08:18:41

相关问题