问题
I have a file which overwrites overlay.xul
that overwrites browser.xul
. I want to implement message passing in a similar way as implemented in chrome extensions.
chrome.manifest-
content helloworld content/
overlay chrome://browser/content/browser.xul chrome://helloworld/content/overlay.xul
overlay chrome://navigator/content/navigator.xul chrome://helloworld/content/overlay.xul
skin helloworld classic/1.0 skin/
style chrome://global/content/customizeToolbar.xul chrome://helloworld/content/overlay.css
How to I register content_script.js
which in my case is overlay.js
?
Overlay.xul -
<script type="application/x-javascript" src="chrome://helloworld/content/jquery.js" />
<script type="application/x-javascript" src="chrome://helloworld/content/overlay.js" />
<script type="application/x-javascript" src="chrome://helloworld/content/background.js" />
Now inside my overlay.js
I'm using -
document.documentElement.addEventListener('click', function(e) {
messageManager.sendAsyncMessage('MyMessenger.MyMessage', {});
}, true);
And the background.js
is-
addMessageListener("MyMessenger.MyMessage", function(obj) {
Firebug.Console.log(obj.name);
}, true);
- What is the correct syntax for message passing?
- How do I configure the connection between content script and browser script?
回答1:
If all you are interested in is really injecting a content script and communicating with it then it should be easier to use the Add-on SDK, particularly the page-mod package. It allows injecting content scripts easily and provides a way to communicate (see "Communicating With Content Scripts" section in the docs I mentioned).
As to messageManager
, it is meant for a multi-process environment but it will work in the current single-process Firefox as well. The main problem with your code above is: addMessageListener
isn't a global function, you should call messageManager.addMessageListener()
. But using messageManager
to pass messages between scripts that are loaded into the same namespace and could call each other directly is an overkill anyway.
To communicate with a content script in the current tab the script in the overlay would do:
gBrowser.selectedBrowser.messageManager.sendAsyncMessage('MyMessenger.MyMessage', {});
And the content script would indeed have addMessageListener
as a global function so this should work:
addMessageListener("MyMessenger.MyMessage", function(obj) {
console.log(obj.name);
});
来源:https://stackoverflow.com/questions/8226042/how-to-implement-message-passing-in-firefox-extension