Execute JS from Firefox extension

匿名 (未验证) 提交于 2019-12-03 03:10:03

问题:

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?

回答1:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!