我正在用Electron创建一个桌面应用程序。单击应用程序上的按钮(由HTML制成)时,我试图运行Python脚本。我通过使用child_process
和spawn
做到了这一点。但是,当我在目录中通过命令提示符(Windows 10)运行npm start
时,我是从document is not defined
获取该renderer.js
的。
我知道有一些关于在Electron中使用ipcMain
和ipcRenderer
的信息,但是我不确定如何使用它。任何帮助表示赞赏。
这是我的文件夹树:
.
├── hello.py
├── index.html
├── main.js
├── node_modules
│ // node modules
├── package-lock.json
├── package.json
├── renderer.js
└── require.js
index.html
:<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="require.js"></script>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="require.js"></script>
<button id="push_me" type="button">Push me</button>
</body>
</html>
main.js
:const {app, BrowserWindow} = require('electron');
const path = require('path');
const url = require('url');
require('./renderer.js');
let win;
function createWindow() {
win = new BrowserWindow({width: 800, height: 600, webPrefences: {nodeIntegration: true}});
win.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}))
win.on('closed', () => {
win = null;
})
}
app.on('ready', createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
})
renderer.js
:var pushMe = document.getElementById('push_me');
pushMe.addEventListener('click', runPython());
function runPython() {
var python = require(['child_process']).spawn('python', ['hello.py']);
python.stdout.on('data', function(data) { console.log(data.toString('utf8')); });
}
hello.py
:print("Hello, world!")
package.json
:{
"name": "app_ui",
"version": "1.0.0",
"description": "",
"main": "main.js",
"scripts": {
"start": "electron ."
},
"author": "",
"license": "ISC",
"dependencies": {
"electron": "^8.1.1",
"jquery": "^3.4.1",
"python-shell": "^1.0.8"
}
}
最佳答案
您正在尝试从主进程访问document
。这是错误的。您只能在渲染器进程内访问DOM API。我建议阅读docs以了解主进程和渲染器进程之间的区别。
您的index.html应该看起来像这样
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="require.js"></script>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="require.js"></script>
<button id="push_me" type="button">Push me</button>
<script src="renderer.js"></script> <!-- load renderer.js here -->
</body>
</html>
并且您应该从main.js中删除
require('./renderer.js');
关于javascript - 为什么在Electron renderer.js文件中未定义文档?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60716184/