electron的双屏异显方案
发表于:2023-11-19 20:23:02浏览:822次
本方案主要是实现了在两个屏幕显示不同的内容,并根据用户操作,使两个屏幕之间可以通过方法调用(通信),使副屏幕执行相应的操作。
所需的硬件前提条件:双屏,且将双屏的显示方式改为“扩展”;
p.s. 本文使用的electron的版本为1.8.8;如使用新版本进行开发,官方出于安全考虑,默认是开启语境隔离模式的,需要在预加载脚本(preload)部分使用contextBridge进行方法处理。
方案的步骤如下:
- 在
/src/main/index.js
文件中,编写增加副屏幕的方法,并在启动的时候,调用此方法
function createOtherWin(){
let displays = screen.getAllDisplays();
//寻找副屏幕
let externalDisplay = displays.find((display) => {
return display.bounds.x !== 0 || display.bounds.y !== 0
})
if (externalDisplay) {
otherWindow = new BrowserWindow({
fullscreen:true,
x: externalDisplay.bounds.x,
y: externalDisplay.bounds.y,
webPreferences: {
nodeIntegration: true,
//配置预加载脚本文件(preload),此处起名为preloadOther
//p.s.路径为绝对路径
preload: require('path').join(app.getAppPath(), 'preloadOther.js')
}
})
//指定副屏幕打开的网页
otherWindow.loadURL(`file://${app.getAppPath()}/src/main/testOtherWin.html`);
otherWindow.on('closed', () => { //这一段放外面的话,如果你电脑没双屏会报错。
otherWindow = null
})
//主进程监听事件示例(用于双屏之间的通信)
//需要预先引入 import { ipcMain } from 'electron'
ipcMain.on('pay-start', (event, detail) => {
otherWindow.webContents.send('pay-start', detail);
})
}
}
//启动的回调方法
app.on('ready', () => {
createWindow();
//启动副屏幕
createOtherWin();
})
123456
- 修改主屏幕的预加载脚本(preload),实现向副屏幕传输消息的方法:
//引入相关的通信组件
const { ipcRenderer } = require('electron')
window.otherScreen = {
payStart: (order) => {
ipcRenderer.send('pay-start', order)
}
}
- 创建副屏幕的预加载脚本(preload)文件,即上文的
preloadOther.js
(p.s. 注意配置文件的路径为绝对路径):
//引入相关的通信组件
const { ipcRenderer } = require('electron')
ipcRenderer.on('pay-start', (event, obj) => {
//接收到的参数
console.log(obj)
//调用副屏幕页面上的方法进行业务操作
onMessage(obj)
})
- 创建测试副屏幕的网页文件(
testOtherWin.html
)(此处为示例文件,较简单)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="application/javascript">
//预加载文件调用此方法进行测试
function onMessage(a) {
alert("onMsg: " + a)
}
</script>
</head>
<body>
<div>
test other win
</div>
</body>
</html>