webContents 模块是 Electron 中的一个模块,用于管理和控制一个页面的渲染过程和交互。每个 BrowserWindow 实例都有一个关联的 webContents 对象,你可以通过这个对象来操作和与渲染进程进行通信。

以下是一些常见的用法和示例:

1. 获取 webContents 对象:

   在主进程中,你可以通过以下方式获取 webContents 对象:
   const { BrowserWindow } = require('electron');

   const mainWindow = new BrowserWindow({ width: 800, height: 600 });
   const webContents = mainWindow.webContents;

2. 向渲染进程发送消息:

   在主进程中,通过 webContents.send 方法向渲染进程发送消息:
   webContents.send('message-channel', 'Hello from main process!');

   在渲染进程中,通过 ipcRenderer 模块接收消息:
   const { ipcRenderer } = require('electron');

   ipcRenderer.on('message-channel', (event, message) => {
     console.log('Received message in renderer process:', message);
   });

3. 执行 JavaScript 代码:

   在主进程中,你可以通过 webContents.executeJavaScript 方法在渲染进程中执行 JavaScript 代码:
   webContents.executeJavaScript('console.log("Hello from executed script!");');

4. 加载 URL:

   在主进程中,你可以通过 loadURL 方法加载 URL:
   webContents.loadURL('https://example.com');

5. 导航控制:

   在主进程中,你可以通过 goBack、goForward 等方法实现导航控制:
   webContents.goBack();
   webContents.goForward();

6. 截图:

   在主进程中,你可以通过 capturePage 方法获取页面的截图:
   webContents.capturePage().then((image) => {
     image.toPNG(); // 获取截图的 PNG 格式
   });

7. 页面事件监听:

   在主进程中,你可以通过 on 方法监听渲染进程发送的事件,例如 dom-ready、did-finish-load:
   webContents.on('dom-ready', () => {
     console.log('DOM is ready!');
   });

这些示例展示了一些常见的 webContents 模块的用法。你可以根据应用的需求,使用 webContents 模块进行更高级的操作,例如向渲染进程注入脚本、处理页面加载过程中的事件、截图等。


转载请注明出处:http://www.pingtaimeng.com/article/detail/10928/Electron