An interesting question indeed.
I just found out through this post on the MozillaZine forum - an easy way to accomplish this. This method basically consists of defining a custom DOM element inside a web page, filling it with some arbitrary attributes, and then using it as the target of the custom event. An event can be captured and used to transfer values ββfrom a web page to an extension.
Webpage (assuming jquery is available)
<script type="text/javascript"> $(document).ready(function(){ $.get("http://mywebsite.net/ajax.php",function(data){ //[...]process data //define a custom element and append it to the document var element = document.createElement("MyExtensionDataElement"); element.setAttribute("application_state", "ready"); document.documentElement.appendChild(element); //create a custom event and dispatch it // using the custom element as its target var ev = document.createEvent("Events"); ev.initEvent("MyExtensionEvent", true, false); element.dispatchEvent(ev); }); }); </script>
Chrome Code:
function myListener(e) { alert("data:" + e.target.getAttribute("application_state")); } function on_specialpage_load(event) { if (event.originalTarget instanceof HTMLDocument && event.originalTarget.location.href == "http://mywebsite.net/myspecialpage.html") { var doc=event.originalTarget; doc.addEventListener("MyExtensionEvent", myListener, false, true); } } gBrowser.addEventListener("DOMContentLoaded",on_specialpage_load,false);
Note that doc.addEventListener has a fourth parameter, indicating that it accepts events coming from untrusted code. However, you can add this event listener selectively so that only trusted pages from your site can pass values ββto the extension.
Andrea Fiore
source share