一、加載遠端頁面
在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>