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

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.

主站蜘蛛池模板: 仪陇县| 浪卡子县| 响水县| 玉环县| 岫岩| 太和县| 绵阳市| 河东区| 汨罗市| 抚松县| 衡东县| 柳江县| 陕西省| 山丹县| 昌黎县| 丰原市| 土默特左旗| 邮箱| 闽清县| 鄄城县| 博罗县| 博罗县| 垦利县| 汝城县| 南宁市| 洪湖市| 安仁县| 呼玛县| 桃园县| 泾阳县| 泾川县| 泌阳县| 进贤县| 桦甸市| 天镇县| 水富县| 贵港市| 厦门市| 宜兰县| 岳阳市| 卢龙县|