I'm 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:
executeJS(content.document, "$('#" + this.id + "').jixedbar({showOnTop:true});");
And this is the result that I get:
<script type="text/javascript">
[object XPCNativeWrapper [object HTMLScriptElement]]
</script>
What's wrong with my code? What's the proper way of execution arbitrary JS script from Firefox extension?
I'm not sure about FF extensions, but in "normal" JS-land, there's no need for the createTextNode
business. Outside of FF extensions, you can use Node.textContent
— though maybe it's different with the XPCNativeWrapper
types.
script.textContent = 'var foo = 1; alert(foo);'
I think the main problem, however, is that you've also got a variable and a parameter both named script
. Try this:
function executeJS(document, scriptContent) {
var script = document.createElement('script');
script.appendChild(document.createTextNode(scriptContent));
document.head.appendChild(script);
}
The type
attribute really is not necessary, BTW.
I just came across this page , which looks like it could be what you're looking for:
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");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.