js实现双屏
双屏显示基础概念
双屏显示通常指通过JavaScript控制两个屏幕(主屏和扩展屏)的内容展示,常见于演示、监控或游戏场景。核心依赖浏览器API(如Window API)或操作系统级多屏管理。
使用Window.open实现简单双屏
通过window.open()打开新窗口并定位到扩展屏,需确保用户已连接多显示器:

// 主屏代码
const secondScreen = window.open(
'secondary.html',
'_blank',
'left=screen.width, width=800, height=600'
);
// secondary.html加载后通信
secondScreen.postMessage('数据同步', '*');
使用Screen API检测多显示器
通过window.screen获取屏幕信息,动态计算窗口位置:
if (window.screen.availLeft > 0) {
// 扩展屏在左侧
window.open('secondary.html', '_blank', `left=${-window.screen.availWidth}`);
} else {
// 扩展屏在右侧
window.open('secondary.html', '_blank', `left=${window.screen.width}`);
}
跨窗口通信
使用postMessage和localStorage同步双屏数据:

// 主窗口发送数据
window.addEventListener('message', (event) => {
if (event.data === 'ready') {
secondScreen.postMessage({ content: '更新内容' }, '*');
}
});
// 副窗口接收数据
window.addEventListener('message', (event) => {
document.getElementById('display').innerText = event.data.content;
});
全屏API控制分屏
利用Element.requestFullscreen()实现单个屏幕全屏:
// 副屏全屏显示
document.documentElement.requestFullscreen().then(() => {
console.log('副屏已全屏');
});
注意事项
- 权限限制:浏览器可能阻止自动弹出窗口,需用户手动允许。
- 屏幕坐标:多显示器环境下
screenX/screenY可能为负值。 - 事件监听:关闭副屏时主屏需移除相关监听,避免内存泄漏。
高级方案:Electron实现
桌面应用可使用Electron的screen模块精准控制多屏:
const { screen } = require('electron');
const displays = screen.getAllDisplays();
displays.forEach((display, index) => {
new BrowserWindow({
x: display.bounds.x,
y: display.bounds.y
});
});






