Run JS from Firefox Extension

I am trying to execute custom JS code from a Firefox extension using:

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

The method call looks like this:

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

And as a result, I get:

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

What happened to my code? What is the correct way to execute an arbitrary JS script from a Firefox extension?

+5
source share
1 answer

I'm not sure about FF extensions, but there is no need for business in a β€œnormal” JS country createTextNode. Outside of FF extensions, you can use Node.textContent- although perhaps this is different from types XPCNativeWrapper.

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

I think the main problem, however, is that you also have a variable and parameter named script. Try the following:

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

type , BTW.


, , , :

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

All Articles