zoukankan      html  css  js  c++  java
  • electron webview加载远程preload方法

    如果渲染进程是通过http协议加载的,webview的preload使用相对路径也会是http协议,但官方文档明确指出preload不支持http协议,如果只想加载本地文件强制可强制写为file协议(原答案链接:https://stackoverflow.com/questions/36103547/electron-preload-script-for-webview-not-working?rq=1):

    <webview src={'http://example.com'} preload={`file://${__dirname}/preload.js`}/>

    但如果渲染进程的页面加载的是远程文件,preload加载本地文件是不利于维护的,遍搜全网没找到答案,考虑在每次渲染进程启动时webview打开之前将远程的preload文件缓存到本地,preload就可以采用file协议了,亲测有效,代码如下:

    const {remote} = require('electron');
    const path = require('path');
    const fs = require('fs');
    
    // preload的本地缓存路径
    // 注意,这里必须是remote.app.getPath的路径,不能为__dirname路径,__dirname打包后的路径不可读写了
    const preloadCachePath = path.join(remote.app.getPath('appData'), './preload/remote.webview.preload.js');
    
    function fetchPreload() {
        return fetch('./preload/webview.preload.js').then(res => res.text()).then(content => {
            if (!fs.existsSync(path.dirname(preloadCachePath))) {
                fs.mkdirSync(path.dirname(preloadCachePath))
            }
            fs.writeFileSync(preloadCachePath, content);
            console.log('fetch remote webview.preload ready', preloadCachePath);
        })
    }
    
    function createWebview() {
        var webview = document.createElement('webview');
        webview.src = url;
        webview.preload = `file://${preloadCachePath}`;
        return webview;
    }
    
    // init内开始渲染,并可调用createWebview创建webview
    fetchPreload().then(init)

    需要注意的是preload文件内的require的相对路径可能(未验证过)会发生变化

  • 相关阅读:
    6-5 函数
    6-2 触发器
    4、MongoDB学习之备份还原
    3、MongoDB学习之固定集合
    2、MongoDB学习之索引的管理
    1、MongoDB学习之基本操作
    JS-01
    | 和 ||,& 和 && 的区别
    正则
    设计测试用例的经验总结
  • 原文地址:https://www.cnblogs.com/feng524822/p/12785666.html
Copyright © 2011-2022 走看看