从Firefox扩展执行JS

从Firefox扩展执行JS

问题描述:

我试图使用从Firefox扩展执行自定义的JS代码:从Firefox扩展执行JS

function executeJS(document, script) { 
    var script = document.createElement('script'); 
    script.setAttribute('type', 'text/javascript'); 
    script.appendChild(document.createTextNode(script)); 
    document.getElementsByTagName('head')[0].appendChild(script); 
} 

方法调用看起来像:

executeJS(content.document, "$('#" + this.id + "').jixedbar({showOnTop:true});"); 

这是结果,我得到:

<script type="text/javascript"> 
    [object XPCNativeWrapper [object HTMLScriptElement]] 
</script> 

我的代码有什么问题? 从Firefox扩展中执行任意JS脚本的正确方法是什么?

我不确定FF扩展,但在“正常”的JS-land中,不需要createTextNode业务。在FF扩展之外,您可以使用Node.textContent —,虽然它可能与XPCNativeWrapper类型不同。

script.textContent = 'var foo = 1; alert(foo);' 

我认为主要然而,问题是,你也有一个变量和参数都命名script。试试这个:

function executeJS(document, scriptContent) { 
    var script = document.createElement('script'); 
    script.appendChild(document.createTextNode(scriptContent)); 
    document.head.appendChild(script); 
} 

type属性实在是没有必要的,BTW。


我只是碰到this page来了,它看起来像它可能是你在找什么:

const XUL = Namespace("xul", "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"); 

function injectScript(name) { 
    // Get the current filename 
    let file = Components.stack.filename; 
    // Strip off any prefixes added by the sub-script loader 
    // and the trailing filename 
    let directory = file.replace(/.* -> |[^\/]+$/g, ""); 

    // Create the script node 
    let script = document.createElementNS(XUL, "script"); 
    script.setAttribute("type", "application/javascript;version=1.8"); 
    script.setAttribute("src", directory + name); 

    // Inject it into the top-level element of the document 
    document.documentElement.appendChild(script); 
} 

// Inject the script 
injectScript("script.js"); 
+0

你真是太好了!变量命名是问题... – spektom 2011-06-05 04:49:20