Javascript 未捕获引用错误:在add.js:1中未定义require
我正试图建立一个简单的电子项目,但解决这个问题有困难。我有一个文件Javascript 未捕获引用错误:在add.js:1中未定义require,javascript,html,node.js,electron,Javascript,Html,Node.js,Electron,我正试图建立一个简单的电子项目,但解决这个问题有困难。我有一个文件add.js,用于向关闭无框架浏览器窗口的按钮添加事件侦听器。我将add.js文件导入到HTML的脚本标记中,如下所示: <script src="add.js"></script> 如果需要,这里是index.js,单击事件侦听器打开此窗口: const electron = require('electron'); const path = require('path'); const Browse
add.js
,用于向关闭无框架浏览器窗口的按钮添加事件侦听器。我将add.js
文件导入到HTML的脚本标记中,如下所示:
<script src="add.js"></script>
如果需要,这里是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)
})
我遇到的问题是,无框架浏览器窗口打开得很好,但我立即得到了“UncaughtReferenceError:”,并且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>
<!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()函数无法在客户端使用它。。。。
如果您想在客户端使用它,您应该在任何地方查看或查找它。添加
webPreferences: {
nodeIntegration: true
},
到新的BrowserWindow实例修复了这个问题 我相当肯定
require()
在浏览器上下文中运行时不起作用(而在NodeJS上下文中,或者通过webpack之类的工具进行捆绑时,它运行得很好)。@arthurakay我肯定遗漏了一些东西,index.js
文件使用require()函数,工作正常。add.html
加载使用require()
的add.js
——这就是抛出错误的地方。我已经有一段时间没有使用电子了,但我记得在某些情况下它有一个混合环境。您的无框架浏览器窗口(app.html
)是一个纯web的上下文。我一定是缺少了什么,然后,index.js
文件使用了require()函数,并且工作正常。我不认为我会这样做。您也可以查看此框架浏览它是否具有相同的实用程序。。。good luckOP谈论的是电子应用程序,而不是在普通浏览器中运行的常规web应用程序。有关电子版本,请参见修订答案
webPreferences: {
nodeIntegration: true
},