Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Triggering a custom event with attributes from a Firefox extension

I have a Firefox extension that modifies the content of the page that the user is looking at. As part of that process the extension needs to trigger a custom event that the extension itself adds to the page source. I am having difficulties passing parameters to that custom event. What am I doing wrong?

Script block inserted into the head of the page:

document.addEventListener("show-my-overlay", EX_ShowOverlay, false, false, true);

function EX_ShowOverlay(e) {
    alert('Parameter: ' + e.index);
    // ...
}

Code in the extension:

var event = content.document.createEvent("Events");
event.initEvent("show-my-overlay", true, true);
event['index'] = 123;
content.document.dispatchEvent(event);

The event gets triggered successfully, but e.index is undefined.

I managed to get it working by creating an element on the page and then having the event handler find the element and read its attributes, but it didn't feel elegant. I want to do it without the element.

EDIT:

I also tried triggering the event with CustomEvent, but it throws an exception in the handler:

var event = new CustomEvent('show-my-overlay', { detail: { index: 123 } });
content.document.dispatchEvent(event);

function EX_ShowOverlay(e) {
    alert('Parameter: ' + e.detail.index);
    // ...
}

Permission denied to access property 'detail'

like image 570
Edgar Avatar asked Sep 11 '13 14:09

Edgar


1 Answers

OP has solved their problem using postMessage. For those of us who actually do have to solve it using CustomEvent (being able to specify message types is useful), here's the answer:

Firefox won't allow the page script to access anything in the detail object sent by the content script via CustomEvent unless you clone the event detail into the document first using the Firefox-specific cloneInto() function.

The following does work over here to send an object from the extension to the page:

var clonedDetail = cloneInto({ index: 123 }, document.defaultView);
var event = new CustomEvent('show-my-overlay', { detail: clonedDetail });
document.dispatchEvent(event);

The Mozilla docs have more detail on cloneInto.

like image 180
Charl Botha Avatar answered Oct 25 '22 11:10

Charl Botha