【发布时间】:2019-05-07 05:36:17
【问题描述】:
我正在尝试设置一个简单的 Electron 项目,但无法解决此问题。我有一个文件add.js,用于将事件侦听器添加到按钮以关闭无框浏览器窗口。我将 add.js 文件导入到 HTML 的脚本标记中,如下所示:
<script src="add.js"></script>
add.js 文件仅包含此事件侦听器:
const electron = require('electron')
const remote = electron.remote
const closeBtn = document.getElementById('closeBtn')
closeBtn.addEventListener('click', (event) => {
let window = remote.getCurrentWindow();
window.close();
})
如果需要,这里是index.js,打开这个窗口的点击事件监听器:
const electron = require('electron');
const path = require('path');
const BrowserWindow = electron.remote.BrowserWindow;
const notifyBtn = document.getElementById('notifyBtn');
notifyBtn.addEventListener('click', (event) => {
const modalPath = path.join('file://', __dirname, 'add.html')
let win = new BrowserWindow({
alwaysOnTop: true,
frame: false,
transparent: true,
width: 400,
height: 200
})
win.loadURL(modalPath)
win.show()
win.webContents.openDevTools();
win.on('close', () => win = null)
})
我遇到的问题是无框浏览器窗口打开得很好,但我立即收到“未捕获的引用错误:”并且 JS 代码没有加载。
我已尝试在此处(stackoverflow)查找问题,但答案表明这是由于尝试在浏览器中运行节点程序引起的。但是,我上面包含的index.js 代码工作得很好,没有错误。
这也是 HTML 文件的代码,以防我发疯:
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>BTCAlert</title>
<link rel="stylesheet" href="../assets/css/main.css">
</head>
<body>
<div class="row">
<div id="price-container">
<p class="subtext">Current BTC USD</p>
<h1 id="price">Loading..</h1>
</div>
<div id="goal-container">
<p><img src="../assets/images/up.svg"><span id="targetPrice">Choose a Target Price</span></p>
</div>
<div id="right-container">
<button id="notifyBtn">Notify Me When...</button>
</div>
</div>
<script src="index.js"></script>
</body>
</html>
add.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="../assets/css/main.css">
<link rel="stylesheet" href="../assets/css/add.css">
</head>
<body>
<p class="notify">Notify me when BTC reaches..</p>
<div class="row2">
<div>
<input id="notifyVal" placeholder="USD">
</div>
<button id="updateBtn">Update</button>
</div>
<a id="closeBtn">Close Window</a><br>
</div>
<script src="add.js"></script>
</body>
</html>
非常感谢任何帮助。
【问题讨论】:
-
我很确定
require()在浏览器上下文中运行时不起作用(而它在 NodeJS 上下文中运行良好,或者通过 webpack 之类的工具进行捆绑时)。 -
@arthurakay 我一定是遗漏了一些东西,
index.js文件使用了 require() 函数并且工作得很好。 -
add.html加载使用require()的add.js- 这就是引发错误的地方。自从我使用 Electron 已经有一段时间了,但我记得它在某些情况下具有混合环境。您的无框浏览器窗口 (app.html) 是一个仅限 Web 的上下文
标签: javascript html node.js electron