Akash Kakkar
Akash Kakkar

Reputation: 335

Electron: How to pass the message/data from preload to renderer?

Basicly I want the renderer to constantly listen for the message from and preload can send the message to renderer anytime. Basicly my scenario is:

  1. Whenever user copies anything to clipboard, the main process will send the message to preload via webContents.send("clipboard-updated");
  2. Main process will save the newly received clip into the database.
  3. Preload will send the message to the renderer upon receiving the message from the main.
  4. Render will fetch the data from the database again and will refresh the UI. this is the whole scenario and here I'm unable to figure out that how do I send the message to renderer so that it can refresh the UI.

Upvotes: 1

Views: 2986

Answers (1)

aabuhijleh
aabuhijleh

Reputation: 2474

You can use Window.postMessage() to send data from preload to renderer

// preload

window.postMessage("your-data", "*");
// renderer

window.addEventListener("message", (event) => {
  // event.source === window means the message is coming from the preload
  // script, as opposed to from an <iframe> or other source.
  if (event.source === window) {
    console.log("from preload:", event.data);
  }
});

Or you can communicate directly from the main process to the renderer process AKA "main world" as seen here in the docs

Upvotes: 3

Related Questions