繁体   English   中英

从 Firefox 扩展执行 JS

[英]Execute JS from Firefox extension

我正在尝试使用 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 领域,不需要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属性确实不是必需的。


我刚看到 这个页面,看起来它可能是你要找的东西:

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");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM