[md] electron webview 和 h5 交互、jsBridge 的实现方式

[TOC]

环境:

electron-vue

jsBridge 创建方式

在 dist-electron 中创建preload.js

//preload.js
window._ipcRenderer = require('electron').ipcRenderer;
window._remote = require('electron').remote;
window.isInElectron  = require('is-electron')
window._platform = process.platform;

设置 preload.js 的文件路径

***在主进程 background.js 中创建主进程下的全局变量,引入preload.js 的文件路径,因为 preload文件路径只支持(file | asar),如果不这样设置怕找不到preload.js 文件路径

function createWindow() {
  // Create the browser window.
  global.shareObject = { // ********这是重点
    preloadPath: path.join(__dirname , 'preload.js')
  }
  win = new BrowserWindow({
    width: 2080,
    height: 1800,
    webPreferences: {
      webviewTag:true ,
      webSecurity : false ,//是否禁用同源策略(上线时删除此配置)
      // Use pluginOptions.nodeIntegration, leave this alone
      // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
      //nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
      nodeIntegration: true
    },
    //  transparent : true ,
    //  frame : false ,
    //  maximizable: false,
    //  resizable: false,
    icon: path.join(__static, 'icon.png')
  })
}
//参考链接:https://www.electronjs.org/docs/api/webview-tag#preload

给webview 设置文件路径

<template>
  <webview :preload="path "></webview>   //  html 部分
</template>
<script>
import { remote , ipcMain } from "electron";
export default {
     data (){ 
        return {
            path : "" ,// preload.js 文件路径
        }
    } ,
    created (){
        let preload = remote.getGlobal('shareObject').preloadPath ; //  这里与第二条的  global.shareObject  相对应
        this.path = preload;
    }
}
</script>

*******通讯部分*******

1. electron webview 部分
var webview = document.querySelector("#webview");
webview.addEventListener('ipc-message', (event) => { //  监听事件(事件名好像只可以是 ipc-message )
        console.log("event.channel : webview");
        console.log(event.channel)
        // Prints "pong"
 })
const obj = {        a : 100 ,        b : 300       }
webview.send('ping' , obj ) // 给 网页  端发送事件 ,并传参过去
2. 网页部分
_ipcRenderer.on('ping', (evt , data) => {    //   接收webview send 过来的事件   (webview.send('ping'))
    console.log( 'ping ')
    console.log( evt , data); // data 就是传过来的数据   
    _ipcRenderer.sendToHost('pong')   //  给 webview 传参用 _ipcRenderer.sendToHost
  })
 document.querySelector("#btn").onclick = () => {
    _ipcRenderer.sendToHost('pong')
  }

给网页中注入js 代码

// webview中

/**
* 方式一   ****************************************************
*/
var webview = document.querySelector("#webview");
let webUserInfoAll = {a:10,b:20,c:30};
webview.executeJavaScript(`window.webUserInfoAll=${JSON.stringify(webUserInfoAll)}`)
      .then( res => {
        console.log( res )
      })
      .catch( err => {
        console.log( err )
      });
// 在网页端通过 window.webUserInfoAll  就可以拿到数据,不过只能webview 单向通讯到网页端,


/**
* 方式二   ****************************************************
*/
//webview代码
var webview = document.querySelector("#webview");
let obj = {a : 30 , b:40}
      webview.executeJavaScript(`getClientMessage(${JSON.stringify(obj)})`)
      .then( res => {
        console.log( res )
      })
      .catch( err => {
        console.log( err )
      });

//网页代码
function getClientMessage ( msg ){
     console.log('getClientMessage' , msg );
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容