[英]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.