一. 监听窗口move和resize事件
mainWin.on('move', () => {
mainWin.webContents.send("window_move");
});
mainWin.on('resize', () =>{
console.log("on resize");
});
ipcRenderer.on("window_move", (ev, arg)=>{
if (!getWinPos()) return false;
let x = winLeft + playerLeft;
let y = winTop + playerTop - scrollTop;
console.log(`on recv window_move: ${x}, ${y}`);
});
二. 调用的dll导出的C接口
// app.js
window.ffi_napi = ffi.Library("./my_win.dll", {
set_callback: ['void', ['pointer']]
});
var c_CallBack = ffi.Callback('int', ['int', 'string'], // 定义'string', js直接传字符串, c++用char*传
function(id) {
console.log(`[callback] ${id}`);
return 456;
});
process.on('exit', () => {
c_CallBack // keep reference avoid gc
})
// call setCallback
window.ffi_napi.set_callback(c_CallBack);
// .h
typedef int (*PFCallback)(int);
DLL_API void set_callback(PFCallback cb);
// .cpp
PFCallback g_cb = nullptr;
DLL_API void set_callback(PFCallback cb) {
sprintLog("set_callback: %x \r\n", cb);
g_cb = cb;
}
void threadProc() {
sprintLog("callback begin: %x \r\n", g_cb);
if (g_cb) {
int ret = g_cb(123);
sprintLog("callback ret: %d \r\n", ret);
g_cb = nullptr;
}
}
threadProc();
三. 离屏渲染
app.disableHardwareAcceleration();
app.once('ready', () => {
win = new BrowserWindow({
webPreferences: {
offscreen: true // 设置离屏渲染
}
})
win.loadURL('http://github.com')
win.webContents.on('paint', (event, dirty, image) => { // 获的渲染的界面图
// updateBitmap(dirty, image.getBitmap())
})
win.webContents.setFrameRate(30) // 设置离屏渲染的帧率
})
四. 如果将某域名添加到白名单, 方便跨域加载
import { session } from 'electron';
session.defaultSession.webRequest.onBeforeSendHeaders({
urls: ["http://*.xxx.com/*"]
} , (details, callback) => {
details.requestHeaders['Referer'] = 'http://www.xxx.com';
callback({ requestHeaders: details.requestHeaders });
});
五. 监听网络状态
const alertOnlineStatus = () => {
window.alert(navigator.onLine ? 'online' : 'offline')
}
window.addEventListener('online', alertOnlineStatus)
window.addEventListener('offline', alertOnlineStatus)
六. 弹出一个简单的页面
const modalPath = path.join('file://', __dirname, '../../xxx.html')
let win = new BrowserWindow({ width: 400, height: 320, modal: true }); // 可设置模态
win.on('close', () => { win = null }); // 对关闭做处理
win.on('resize', updateReply) // 监听大小变化
win.getSize() // 获得大小
win.on('move', updateReply) // 监听移动变化
win.getPosition() // 获得位置
win.reload() // 重新加载页面
win.on('focus', hideFocusBtn) // 监听到获得焦点
win.on('blur', showFocusBtn) // 监听到失去焦点,
win.focus() // 触发抢到焦点
win.loadURL(modalPath); // 加载一个简单的html
win.show();
win.on('unresponsive', () => {}) // 程序没响应了
win.on('responsive', () => {}) // 程序有响应
七. 实现菜单
const { BrowserWindow, Menu, MenuItem, ipcMain, app } = require('electron')
const menu = new Menu()
menu.append(new MenuItem({ label: 'Hello' }))
menu.append(new MenuItem({ type: 'separator' }))
menu.append(new MenuItem({ label: 'Electron', type: 'checkbox', checked: true }))
app.on('browser-window-created', (event, win) => {
win.webContents.on('context-menu', (e, params) => {
menu.popup(win, params.x, params.y)
})
})
ipcMain.on('show-context-menu', (event) => {
const win = BrowserWindow.fromWebContents(event.sender)
menu.popup(win)
})
八. WebView的显示(官方不推荐)
<webview
id="webview"
ref="webview"
:src="http://www.xxx.com" // 地址
httpreferrer="http://www.yyy.com" // 遇到跨域问题, 可以跳过
disablewebsecurity // 关闭网络安全
class="webview"
nodeintegration // 允许启用node功能
allowpopups // 允许弹窗
/>
// 内部触发事件, 发送参数给外部
click(e){
e.stopPropagation()
let ipcRenderer = require('electron').ipcRenderer
var paramsJSON = JSON.stringify({cellId: cellId, url: dom.url})
ipcRenderer && ipcRenderer.sendToHost(paramsJSON)
}
// 外部接收事件, 解析参数
var webview = document.getElementById("foo");
webview.addEventListener("did-stop-loading", loadstop); // 加载好了
webview.addEventListener('ipc-message', (event) => { // 收到内部的消息
if (event.channel) {
let params = JSON.parse(event.channel)
}
})
<webview>.loadURL(url[, options])
九. Iframe跨域显示(WebView的替代方案)
webPreferences:{
webSecurity: false,
allowRunningInsecureContent: true
},
app.commandLine.appendSwitch('disable-site-isolation-trials'); // 关闭跨域限制
let myIframe = document.getElementById('myIframe'); // 获取iframe, 设置内部window.external
myIframe.contentWindow.external.cbSendEvent = (evt)=>{
console.log(`[owner] cbSendEvent receive ${JSON.stringify(evt)}`);
}