Link between firefox extension and javascript page

I am developing a javascript / html web application with a Firefox child extension.

The javascript application page makes several XHR calls immediately after the page loads to display and display all the content that the page requires.

Is there a way without polling the DOM that my extension might know that the page initialization procedures are complete?

+7
javascript firefox firefox-addon
source share
2 answers

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.

+11
source share

You can connect to the XMLHttpRequest object from your extension and track requests, similar to what this GreaseMonkey script does ( description ). Add the wrapper to onreadystatechange in the same way that it added an open wrapper that notifies the extension when completed. You may also need some kind of code that allows you to do this only when visiting your own page.

Firebug does similar things for its Net panel, the code base for this is a bit intimidating though :) I also looked at the Firebug Lite watchXHR functions , but this code is too cunning for me if you can solve it, let me know.

+1
source share

All Articles