google-chrome-extension

Downsides to using window.dispatchEvent to send messages from content script to page scripts?


When sending data from a content script to a page script, both the Chrome docs and the MDN docs provide examples with window.postMessage(). However, window.dispatchEvent() seems to work just fine too, and allows customizing the event name with a CustomEvent. Are there any security or capability downsides to using dispatchEvent instead of postMessage?


Solution

  • There are none and it's the other way around, window.postMessage is a worse solution:

    The only reason to use window.postMessage is to communicate with the website or with another document in a cross-origin frame or window.