简体   繁体   中英

interaction beetween firefox xul estension and a web page

I'm writing a firefox xul extension, and I must have an interaction beetween the web page and extension.

Example: If I press a link from the page I want to call a function in the xul extension. Anyone know if there is a way?

Thanks a lot

Yes, you can do this. You'll need to access page content with the content object.

In your extension code you can select all links and then add an eventListener:

allLinks = content.document.getElementsByTagName("a"),

for (var i=0, il=allLinks.length; i<il; i++) {
    elm = allLinks[i];
    elm.addEventListener("click", nowclicked, false);
}

And then your event listener would look something like:

nowclicked : function () {
    alert("a linked was clicked!");
}

If you need a working example, I've modified the Link Target Finder extension by Robert Nyman to add an alert when links are clicked. The modified code is in linkTargetFinder.js .

See MDN example for Sending data from unprivileged document to chrome document .

Basically, in your chrome code you have to add a listener:

// The last value is a Mozilla-specific value to indicate untrusted content is allowed to trigger the event.
document.addEventListener("MyExtensionEvent", function(e) {myExtension.myListener(e);}, false, true);

and fire the event from content script. Note that document in the following is the contentDocument not XulDocument

var evt = document.createEvent("Events");
evt.initEvent("MyExtensionEvent", true, false);
element.dispatchEvent(evt);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM