[英]Code runs fine on console but gives error when injected by browser extension(works on chrome not in firefox)
[英]Executing injected Javascript code in a page when developing a Firefox extension
我正在開發一個Firefox擴展,它在狀態欄中放置一個按鈕。 單擊該按鈕時,擴展會將一些Javascript注入當前頁面。 這個Javascript有一個我想用一些參數調用的函數。 我已經管理了注入代碼,我已經通過Firebug檢查了頁面並驗證了JS已被注入。 如何從我的擴展程序中調用頁面中的Javascript函數?
- 更多信息
這是我用來注入Javascript的代碼:
var doc = window.content.document;
//Add the script
var visibilityJS = doc.createElement("script");
visibilityJS.setAttribute("type", "text/javascript");
visibilityJS.setAttribute("charset", "UTF-8");
visibilityJS.setAttribute("src", "chrome://visibility/content/scripts/visibility.js");
head.appendChild(visibilityJS);
//Call the function
alert("Executing testfunction");
window.content.document.defaultView.testFunction();
..以及我要注入的JS文件中的代碼。 即visibility.js
window.testFunction = function() {
alert("Message");
}
謝謝。
這很有效。 我不知道技術性。 我從Felix獲得了部分解決方案,並從此處獲得了部分解決方案。
window.content.document.defaultView.wrappedJSObject.testFunction();
如果在注入的代碼中聲明了一個全局變量(或者顯式設置了window
對象的屬性),那么通過gBrowser
對象,一種方法是從擴展中獲取對該元素的引用:
gBrowser.contentDocument.defaultView.yourObject
^-- HTML document ^
object |-- window object
但是,當您在代碼中使用window
和document
時要小心。 根據上下文,它可能會引用Firefox窗口或網站窗口對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.