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

  • 相关阅读:
    SELFJOIN
    lLinux编程大全
    一个基础但是隐晦的c++语法问题
    cocos2dx内存优化
    iOS和android游戏纹理优化和内存优化(cocos2dx)
    STL学习小结
    C++11
    游戏资源打包
    C++ '__FILE__' and '__LINE__
    Cocos2dx纹理优化的一些方案
  • 原文地址:https://www.cnblogs.com/feng524822/p/12785666.html
Copyright © 2011-2022 走看看