Reputation: 700
I am developing a firefox extension that retrieves data from the webpage in the current tab. I am loading a script into the webpage when the user clicks on the overlay toolbar button which does some processing and gets information from the web page. I want to display that information in a popup window.
I am using the following api to load the script:
var loader = Components.classes[ "@mozilla.org/moz/jssubscript-loader;1" ].getService( Components.interfaces.mozIJSSubScriptLoader );
loader.loadSubScript("chrome://dynamonote/content/contentscript.js");
I need to send the object created in contentscript.js and display it in popup.html which is displayed when user clicks on the toolbar icon.
I am receiving the gBrowser is not defined error when I execute the code. The details of the code I am using is given below:
In the onCommand of the overlay, I am calling the following function:
var Popup = {
showPopup: function() {
window.open("chrome://dynamonote/content/popup.html", "dynamonote", "chrome");
}
};
This shows a popup window. In the init function of popup.html which is called when the page loads, I am executing the following code:
function loadContentScript() {
Components.utils.reportError("loadContentScript() called");
gBrowser.selectedBrowser.messageManager.loadFrameScript("chrome://dynamonote/content/contentscript.js", true);
gBrowser.selectedBrowser.messageManager.addMessageListener("foomessage", onMessage);
Components.utils.reportError("loadContentScript() executed");
}
The following code is executed in the contentscript.js file:
(function() {
Components.utils.reportError("-- content script -- ");
var doc = content.document;
//Do something here
var data = {
"time": new Date().toLocaleString()
};
Components.utils.reportError("-- content script -- found something");
sendSyncMessage("foomessage", onMessage(data));
})();
Please help me out with this.
Upvotes: 0
Views: 931
Reputation: 57681
If you want content scripts in a classic Firefox extension then mozIJSSubScriptLoader
is the wrong tool - the "content script" will keep advanced privileges and likely cause security issues. You could use the message manager instead (ignore the talk about process separation, it is irrelevant for the desktop Firefox). So to load your script into the currently selected tab you would use the following code:
gBrowser.selectedBrowser.messageManager
.loadFrameScript("chrome://dynamonote/content/contentscript.js", true);
gBrowser.selectedBrowser.messageManager.addMessageListener("foomessage", onMessage);
function onMessage(obj)
{
alert("Received object from content script: " + obj.toSource());
}
Note that you should remove that message listener when it isn't needed any more. And to send a message back the content script would use code like this:
sendAsyncMessage("foomessage", obj);
Upvotes: 1