Electron 从低版本升级到高版本 - webview通信的改造

旧版本的webview,在通信时,是通过webview.contentWindow.postMessage()跟你的url进行通信的,如果你们一开始就是使用ipcRenderer的话,那应该就不用调整了,但是如果一开始就只是使用普通的postMessage的话,就要改造一下,下面我们来改改webview的通信升级。

首先,改写一下webview需要加载的preload文件,添加contextBridge内容;

javascript 复制代码
const { contextBridge, ipcRenderer } = require('electron');
contextBridge.exposeInMainWorld('electron', {
    // 这里可以添加发送到主进程的消息
sendMessageToMain: message => {
    ipcRenderer.send('message-from-webview', message);
    ipcRenderer.sendToHost('message-from-webview', message);
  },
  onMessageFromRenderer: callback => ipcRenderer.on('ipc-message', (event, ...args) => callback(...args)),
});


// 把具体内容注入到你的webview里面

window.addEventListener('DOMContentLoaded', () => {
  const style = document.createElement('style');
  style.textContent = 'img {user-drag: none; -webkit-user-drag: none}';
  document.head.appendChild(style);
  const scriptTag = document.createElement('script');
  scriptTag.textContent = `
    (function (global) {
      window.electron.onMessageFromRenderer((msg, ...arg) => {
        // 这里可以添加回调发送给主进程的内容
        window.electron.sendMessageToMain();
    });
    })(window);
    console.debug("Script 注入成功!");
  `;
  document.body.appendChild(scriptTag).parentNode.insertBefore(scriptTag, document.body.lastChild);
});

好了,这个时候,你在加载完webview之后,就可以往里面发消息了;

javascript 复制代码
    webview.send('ipc-message', {type: 'demo'});

webview的改造不多,还有就是一些使用webview时需要注意的方法调用问题,就看看文档吧;

https://github.com/electron/electron/blob/28-x-y/docs/api/webview-tag.md

相关推荐
子兮曰29 分钟前
async/await高级模式:async迭代器、错误边界与并发控制
前端·javascript·github
恋猫de小郭40 分钟前
2026 Flutter VS React Native ,同时在 AI 时代 VS Native 开发,你没见过的版本
android·前端·flutter
GIS之路3 小时前
ArcGIS Pro 中的 Notebooks 入门
前端
IT_陈寒4 小时前
React状态管理终极对决:Redux vs Context API谁更胜一筹?
前端·人工智能·后端
Kagol5 小时前
TinyVue 支持 Skills 啦!现在你可以让 AI 使用 TinyVue 组件搭建项目
前端·agent·ai编程
柳杉5 小时前
从零打造 AI 全球趋势监测大屏
前端·javascript·aigc
simple_lau5 小时前
Cursor配置MasterGo MCP:一键读取设计稿生成高还原度前端代码
前端·javascript·vue.js
睡不着先生5 小时前
如何设计一个真正可扩展的表单生成器?
前端·javascript·vue.js
天蓝色的鱼鱼5 小时前
模块化与组件化:90%的前端开发者都没搞懂的本质区别
前端·架构·代码规范
明君879975 小时前
Flutter 如何给图片添加多行文字水印
前端·flutter