[英]Executing injected Javascript code in a page when developing a Firefox extension
I'm developing a Firefox extension which places a button in the status bar. 我正在开发一个Firefox扩展,它在状态栏中放置一个按钮。 When the button is clicked, the extension injects some Javascript into the current page.
单击该按钮时,扩展会将一些Javascript注入当前页面。 This Javascript has a function that I would like to invoke with some parameters.
这个Javascript有一个我想用一些参数调用的函数。 I've managed injecting the code, I've inspected the page through Firebug and verified that the JS has been injected.
我已经管理了注入代码,我已经通过Firebug检查了页面并验证了JS已被注入。 How can I call a Javascript function in the page from my extension?
如何从我的扩展程序中调用页面中的Javascript函数?
--More information - 更多信息
Here's the code that I'm using to inject my 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();
..and the code inside my JS file that i'm going to inject. ..以及我要注入的JS文件中的代码。 ie visibility.js
即visibility.js
window.testFunction = function() {
alert("Message");
}
Thanks. 谢谢。
If you declare a global variable in your injected code (or explicitly set a property of the window
object), then one way do get a reference to this element from your extension, is via the gBrowser
object: 如果在注入的代码中声明了一个全局变量(或者显式设置了
window
对象的属性),那么通过gBrowser
对象,一种方法是从扩展中获取对该元素的引用:
gBrowser.contentDocument.defaultView.yourObject
^-- HTML document ^
object |-- window object
Be careful though, when you use window
and document
inside your code. 但是,当您在代码中使用
window
和document
时要小心。 Depending on the context it might refer to the Firefox window or the website window object. 根据上下文,它可能会引用Firefox窗口或网站窗口对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.