从Firefox扩展执行JS

时间:2011-06-05 04:19:21

标签: javascript firefox firefox-addon

我正在尝试使用以下命令从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脚本的正确方法是什么?

1 个答案:

答案 0 :(得分:3)

我不确定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");
相关问题