如果渲染过程是通过http协议加载的,webview的preload使用的相对路径也会是http协议,但是官方文档明确表示preload不支持http协议。如果只想加载本地文件,可以强制写成文件协议(原回答链接:https://stackoverflow.com/questions/36103547/electron-preload-script-for-webview-not-working?rq=1):但是如果渲染过程的页面加载远程文件,preload加载本地文件不利于维护。我搜索了整个网络,没有找到答案。第二次渲染进程启动时,远程preload文件在webview打开前缓存到本地,preload可以使用file协议。亲测有效。代码如下:const{remote}=require('electron');constpath=require('path');constfs=require('fs');//preload的本地缓存路径//注意这里必须是remote.app.getPath的路径,不是__dirname的路径,__dirname打包的路径无法读写constpreloadCachePath=path.join(remote.app.getPath('appData'),'./preload/remote.webview.preload.js');functionfetchPreload(){returnfetch('./preload/webview.preload.js').then(res=>res.text()).then(content=>{if(!fs.existsSync(path.dirname(preloadCachePath))){fs.mkdirSync(path.dirname(preloadCachePath))}fs.writeFileSync(预加载缓存路径,内容);console.log('fetchremotewebview.preloadready',preloadCachePath);})}functioncreateWebview(){varwebview=document.createElement('webview');webview.src=url;webview.preload=`file://${preloadCachePath}`;returnwebview;}//在init中开始渲染,并调用createWebview创建webviewfetchPreload().then(init)需要注意preload文件中require的相对路径可能(未验证)变化