Browser extensions and event emitters

Question

Hey, anyone here familiar with browser extensions and event emitters? I have two questions:

  1. Can different extensions emit the same eventListener? Let's say I want a website to listen to 'extensions' event, could different browser extensions emit and use the same name?

  2. Can these extensions send information through this event? Like a js object?

So I would like to trigger from the website something like

window.addEventListener('extensions', (extensionInfo)=>{
 numOfExtensions =+ 1;
console.log(extensionInfo)
})

Not sure if this is possible or if there would be a conflict between the extensions when triggering emit.

Thanks

Posted May 2, 2023, 5:15 AM UTC

24
de-ancientone•

Here are the answers

  1. Yes you can dispatch events with the same names from different extension contexts as long as the top context is the website where the events are being listened to.
  2. Yes you can send data with the event as long as the data is primitive value or transferable object.

Here is an example

// Extension context
const event = new CustomEvent('extensions', {
 detail:  {// the data here}
})

And in the top context

window.addEventListener('extensions', (e)=>{
 console.log(e.detail)
})
1
NineThundersOP•

Thanks a lot for the answer, I have one last question, let's say this extensions are competing each other, would it be possible for one extension to cheat and stop or prevent others from using the emitter?

1
de-ancientone•

Possible if the event being dispatched is cancellable (the cancellable option should be defined on every CustomEvent being dispatched) but it's not a feasible solution as it results in race conditions since the extensions are not always loaded in the same order and could result in unexpected behavior.

2
de-ancientone•

It's not a tested answer btw.

1