一、加载远端页面
在main.js内通过 BrowserWindow 对象加载远端页面,如下所示:
'use strict';
const electron = require('electron')
const globalShortcut = electron.globalShortcut;
// Module to control application life.
const app = electron.app
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow
global.releaseVersion = false;
function createWindow () {
// 创建窗体
mainWindow = new BrowserWindow({width: 800, height: 800})
// 注册打开控制台的快捷键
globalShortcut.register('CommandOrControl+P+0', function () {
mainWindow.webContents.openDevTools();
})
// 加载首页
// mainWindow.loadURL('file://' + __dirname + '/index.html')
mainWindow.loadURL('http://localhost:8888/electron/index.html')
// 创建窗体时打开控制台
mainWindow.webContents.openDevTools()
// 监听关闭窗体事件
mainWindow.on('closed', function () {
mainWindow = null
})
}
app.on('ready', createWindow)
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', function () {
if (mainWindow === null) {
createWindow()
}
})
以上 mainWindow.loadURL('http://localhost:8888/electron/index.html') 加载远端页面。
二、注入SDK接口到远端页面
有的时候,我们在node的基础上拓展了我们自己的模块,也就是我们说的C/C++拓展模块node_module(这里我们以SDK来描述),但是这些SDK需要提供给第三方调用,这时就需要在我们加载第三方页面的时候将我们的SDK相关接口注入到加载的页面内,这样就可以在待加载的远端页面内调用我们SDK提供的接口了,如下所示:
mainWindow.webContents.executeJavaScript(`
let basePath = process.cwd();
window.Qbian = require(basePath + '//resources//app//index.js');
console.info('--executeJavaScript export Object --> ', window.Qbian);
`);
index.js 内就是我们提供给第三方调用的SDK相关接口了,示例如下:
const http = require('http');
const fs = require('fs');
module.exports = { http, fs };
三、远端调用
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>index</title>
</head>
<body>
<h1 id="content">Hello world .</h1>
<button type="button" id="button">alert</button>
<!-- 远端页面加载jquery需要使用以下方式 -->
<script>if (typeof module === 'object') {window.module = module; module = undefined;}</script>
<script src="./jquery.min.js" charset="utf-8"></script>
<script>if (window.module) module = window.module;</script>
<script type="text/javascript">
$(function() {
// 这样就可以调用我们 SDK 导出的相关接口(fs)了
console.info(window.Qbian.fs);
$('#button').on('click', function() {
alert($('#content').html());
});
});
</script>
</body>
</html>
本文介绍了如何在Electron应用中加载远端页面,并将自定义的SDK接口注入到这些页面,以便第三方可以在远端页面上调用这些接口。首先,通过BrowserWindow加载远端页面,然后详细阐述了如何将SDK接口注入到页面中,最后讨论了远端页面如何调用这些注入的接口。

942

被折叠的 条评论
为什么被折叠?



