Mic*_*tor 5 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);
}
Run Code Online (Sandbox Code Playgroud)
方法调用如下所示:
executeJS(content.document, "$('#" + this.id + "').jixedbar({showOnTop:true});");
Run Code Online (Sandbox Code Playgroud)
这是我得到的结果:
<script type="text/javascript">
[object XPCNativeWrapper [object HTMLScriptElement]]
</script>
Run Code Online (Sandbox Code Playgroud)
我的代码出了什么问题?从Firefox扩展中执行任意JS脚本的正确方法是什么?
我不确定 FF 扩展,但在“正常”JS 领域,不需要这种createTextNode业务。除了 FF 扩展之外,您还可以使用Node.textContent- 尽管类型可能有所不同XPCNativeWrapper。
script.textContent = 'var foo = 1; alert(foo);'
Run Code Online (Sandbox Code Playgroud)
然而,我认为主要问题是您还有一个名为 的变量和一个参数script。尝试这个:
function executeJS(document, scriptContent) {
var script = document.createElement('script');
script.appendChild(document.createTextNode(scriptContent));
document.head.appendChild(script);
}
Run Code Online (Sandbox Code Playgroud)
顺便说一句,该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");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4175 次 |
| 最近记录: |