Samuelint
Samuelint

Reputation: 53

electron - window.postMessage to talk between preload and renderer with specific target origin

I would like to validate/differentiate the origin of a message using the targetOrigin of postMessage between preload.js and renderer.js with contextIsolation enabled.

So if a message come from preload.js, the originTarget being something like file://preload.js, and from renderer file://renderer.js.

Setting file://preload.js or file://renderer.js, make the error Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('file://') does not match the recipient window's origin ('file://')..

Does someone know how to achieve what I’m trying to achieve? Thank you

Upvotes: 3

Views: 4113

Answers (1)

ford04
ford04

Reputation: 74750

To quote MDN web docs:

Lastly, posting a message to a page at a file: URL currently requires that the targetOrigin argument be "*". file:// cannot be used as a security restriction; this restriction may be modified in the future.

So in preload.js you need to use * as targetOrigin:

window.addEventListener("DOMContentLoaded", () => {
  window.postMessage({ type: "fooType", text: "barMsg" }, "*")
})

In the receiving renderer (webpage), restrict message processing to file:// scheme and window object reference for security reasons:

window.addEventListener(
  "message",
  event => {
    if (event.origin === "file://" && event.source === window) {
      console.log(event.data)
    }
  },
  false
)

This will also work with a more restrictive config as follows (webPreferences for BrowserWindow):

{
  nodeIntegration: false,
  contextIsolation: true,
  enableRemoteModule: false,
  preload: path.join(__dirname, "preload.js")
}

Upvotes: 4

Related Questions