Reputation: 762
I am creating a desktop app with Electron. I am trying to run a Python script when I click a button (made from HTML) on the app. I did this by using child_process
and spawn
. However, when I run npm start
with command prompt (Windows 10) in the directory, I am getting that document is not defined
from renderer.js
.
I know there is something about using ipcMain
and ipcRenderer
in Electron but I am not sure how to use that. Any help is appreciated.
Here is my folder tree:
.
├── 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"
}
}
Upvotes: 0
Views: 1990
Reputation: 2464
You're trying to access document
from the main process. This is wrong. You can only access DOM APIs inside renderer processes. I recommend reading the docs to know the differences between main and renderer processes.
Your index.html should look like this
<!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>
and you should remove require('./renderer.js');
from main.js
Upvotes: 1