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的相对路径可能(未验证过)会发生变化

  • 相关阅读:
    java循环遍历map
    java获取天气信息
    java使用json抛出org.apache.commons.lang.exception.NestableRuntimeException解决方案
    eclipse中如何导入jar包
    ext之关键字mixins、statics、require
    ext等待提示
    java保留两位小数的方法
    js循环便利json数据
    java计算一个月有多少天和多少周
    python--decorator装饰器
  • 原文地址:https://www.cnblogs.com/feng524822/p/12785666.html
Copyright © 2011-2022 走看看