如何在JavaScript中实现类似C#的跨窗口模拟键盘输入功能
JavaScript实现跨窗口模拟键盘输入的可行方案
首先明确JS的运行环境权限限制:浏览器端JS默认运行在安全沙箱内,没有系统级API调用权限,无法向浏览器外的其他窗口发送键盘输入,仅Node.js、Electron等拥有系统权限的JS运行环境可以实现和你提供的C#代码一致的效果。
Node.js 环境实现(Windows平台,和C#逻辑完全对齐)
你可以通过ffi-napi调用系统user32.dll接口查找窗口、激活窗口,再用robotjs模拟键盘输入,实现步骤如下:
- 安装依赖包
npm install ffi-napi ref-napi ref-wchar-napi robotjs
注意:上述包为原生模块,安装前需要配置好node-gyp对应的编译环境(Windows下需要安装Visual Studio生成工具)
- 实现代码
const ffi = require('ffi-napi'); const wchar = require('ref-wchar-napi'); const robot = require('robotjs'); // 绑定user32.dll的系统API const user32 = ffi.Library('user32.dll', { // 查找窗口,宽字符版本适配中文窗口标题 FindWindowW: ['int', ['int', wchar.string]], // 将指定窗口置为前台 SetForegroundWindow: ['bool', ['int']] }); // 查找指定标题的记事本窗口 // 英文系统窗口标题替换为 "Untitled - Notepad" const targetHwnd = user32.FindWindowW(0, '无标题 - 记事本'); if (!targetHwnd) { console.log('未找到目标窗口'); process.exit(1); } // 激活目标窗口 user32.SetForegroundWindow(targetHwnd); // 模拟按下A键 robot.keyTap('a');
Electron 环境实现
如果是用Electron开发桌面应用,直接在主进程中复用上述Node.js代码即可,渲染进程如果需要触发操作,通过IPC通道通知主进程执行即可。
浏览器端降级方案
如果必须在浏览器环境中使用,仅能实现同源页面间的模拟按键传递,无法触达浏览器外的系统窗口,实现逻辑如下:
// 父窗口:向同源的弹出窗口/iframe发送按键通知 const targetWin = window.open('./sub-page.html'); targetWin.postMessage({ type: 'simulateKey', key: 'a' }, location.origin); // 子窗口:监听消息并触发当前页面的按键事件 window.addEventListener('message', (e) => { if (e.origin !== location.origin) return; if (e.data.type === 'simulateKey') { const keyEvent = new KeyboardEvent('keypress', { key: e.data.key }); document.activeElement.dispatchEvent(keyEvent); } });
内容的提问来源于stack exchange,提问作者Lorenzo Beronilla
相关产品推荐
相关产品推荐

