官术网_书友最值得收藏!

  • Electron Projects
  • Denys Vuika
  • 352字
  • 2021-06-24 12:14:38

Sending messages to the renderer process

Now, we can send messages from the main process back to the renderer. According to our initial scenario, we are going to handle application menu clicks and let the renderer process know about user interactions.

To send messages to the renderer process, we need to know what window we should address. Electron supports multiple windows with different content, and our code needs to know or figure out which window contains the editor component. For the sake of simplicity, let's access the focused window object since we have only a single-window application right now:

  1. Import the BrowserWindow object from the Electron framework:
      const { BrowserWindow } = require('electron');

The format of the call is as follows:

      const window = BrowserWindow.getFocusedWindow();
window.webContents.send('<channel>', args);

At this point, we have communication handlers from both areas, that is, the browser and Node.js. It is time to wire everything with a menu item.

  1. Update your menu.js file and provide a Toggle Bold entry that sends a toggle-bold message using our newly introduced editor-event channel. Refer to the following code for implementation details:
      const template = [
{
label: 'Format',
submenu: [
{
label: 'Toggle Bold',
click() {
const window = BrowserWindow.getFocusedWindow();
window.webContents.send(
'editor-event',
'toggle-bold'
);
}
}
]
}
];

Let's check whether the messaging process works as expected.

  1. Run the application with the npm start command, or restart it, and toggle the Developer Tools.
  2. Note that you also have the Format menu, which contains the Toggle bold subitem. Click it and see what happens in the browser console output in the Developer Tools:
  1. The Terminal output should contain the following text:
      > DEBUG=true electron .

Received reply from web page: Page Loaded
Received reply from web page: Received toggle-bold

This is a great result! As soon as we click on the application menu button, the main process finds the focused window and sends the toggle-bold message. The renderer process handles the message in Javascript and posts it to the browser console. After that, it replies to the message, and the main process receives and outputs the response in the Terminal window.

主站蜘蛛池模板: 黄大仙区| 安福县| 饶阳县| 唐海县| 江安县| 广宁县| 喀喇沁旗| 民丰县| 桓台县| 治多县| 沁阳市| 西畴县| 安新县| 大余县| 玉门市| 武义县| 汤阴县| 南充市| 石门县| 林芝县| 稻城县| 英山县| 宝山区| 车致| 南阳市| 昭苏县| 昭通市| 泰来县| 成安县| 郑州市| 沧源| 临沭县| 汉寿县| 阆中市| 甘南县| 兰西县| 彭山县| 兰州市| 朝阳市| 枣庄市| 贡觉县|