【发布时间】:2019-11-17 19:13:32
【问题描述】:
当我的index.js 文件中的“q”键被按下时,我试图向index.html 上的脚本发送一条消息,但我真的不知道为什么它不能正常工作。
这是我的 js 文件
const url = require('url');
const path = require('path');
const {app, BrowserWindow, globalShortcut, ipcMain, webContents} = require('electron');
let mainWindow;
app.on('ready', function(){
// Create new window
mainWindow = new BrowserWindow({
backgroundColor: '#000000',
fullscreen : true,
frame : false,
icon : __dirname + "/res/icon.jpg",
webPreferences: {
nodeIntegration : true
}
});
// Load html in window
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes:true
}))
globalShortcut.register('Esc', () => {
app.quit();
});
globalShortcut.register('q', () => {
leftLight();
});
});
function leftLight() {
mainWindow && mainWindow.webContents.send('key-pressed-q');
console.log("Sending q pressed to html...");
}
还有html
<!DOCTYPE html>
<html lang="en">
<meta name="viewport" content="width=device-width, initial-scale=1">
<head>
<link rel="stylesheet" href="styles.css">
<title>Document</title>
</head>
<body>
<div class = rect_green> <h2 class=blocktext >LEFT FENCER</h2></div>
<div class = rect_red><h2 class=blocktext> RIGHT FENCER</h2> </div>
<div class = crono> <h2 class=crontext>3:00</h2></div>
</body>
<script type="text/javascript">
var ipc = require('electron').ipcRenderer;
ipc.on('key-pressed-q', (e) => {
//var element = document.getElementsByClassName("rect_green");
//element.style["background-color"] = "yellow";
console.log("q pressed in html file");
});
</script>
</html>
检测到按下的键,但 ipcRenderer 未收到消息。我的代码有错误吗?
【问题讨论】:
-
渲染器进程控制台是否出现错误?
-
您好,如果以下任何答案对您有所帮助,请随时点赞并接受:)
-
@Mike 他们都没有帮助,但是,重新启动 Visual Code 而不对代码进行任何更改解决了它。我不知道为什么。
-
为什么你认为它不起作用?您是否检查了 您的开发工具控制台 中的消息? (为我工作)
-
@pergy 我关闭并打开 VSC,突然它开始收到消息。我真的很惊讶,因为文件被保存了。我认为有时只是重新启动一切正常......
标签: javascript node.js electron