Firing a custom event with attributes from the Firefox extension

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

The block script is inserted in the head part of the page:

 document.addEventListener("show-my-overlay", EX_ShowOverlay, false, false, true); function EX_ShowOverlay(e) { alert('Parameter: ' + e.index); // ... } 

Code in extension:

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

The event fires successfully, but e.index is undefined.

I managed to get it to work by creating an element on the page, and then the event handler found the element and read its attributes, but it did not look elegant. I want to do this without an element.

EDIT:

I also tried to raise an 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); // ... } 

Access denied

+4
source share
2 answers

You cannot access expandos (additional properties defined on the prototype's own object) across security boundaries. The security boundary in this case is between the fully privileged chrome (add-on) code and the unprivileged website code.

So, you need to transfer data using something β€œstandard”. The CustomEvent would do, however your code is wrong. You must properly call the constructor or initCustomEvent() :

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

Another alternative is the postMessage API .

+2
source

OP solved its problem using postMessage . For those of us who really need to solve them using CustomEvent (the ability to specify message types is useful), here is the answer:

Firefox will not allow the script page to access anything in the detail object sent by the script content via CustomEvent unless you first hide the event detail in the document using the cloneInto() function specific to Firefox.

To send an object from the extension to the page, the following is performed:

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

Mozilla docs have more details about cloneInto .

+2
source

Source: https://habr.com/ru/post/1501674/


All Articles