Reputation: 852
I am trying to create a quote widget on electron. For renderer process, I created index.js and coded like below
console.log('from renderer');
var request = require('request');
const electron = require('electron');
var url ="https://quotesondesign.com/wp-json/wp/v2/posts/?orderby=rand&_="+rnd;
request(url, function(error, response, body) {
if(error)
{
document.getElementById("quote").innerHTML = 'Unable to fetch the quote plaese check the network connection';
return;
}
let bodyJSON = JSON.parse(body);
console.log(bodyJson);
let randomQuote = bodyJSON[0]["content"]["rendered"];
document.getElementById("quote").innerHTML = randomQuote;
});
And index.html has
<div id="quote">
</div>
<script src="index.js">
// require ('index.js');
</script>
If I use require ('index.js');
in script
tag, it doesn't work. So I used src="index.js"
. Now renderer process works but on console, it shows "Uncaught ReferenceError: require is not defined at index.js:3"
My 1st query is why require ('index.js');
on script
tag doesn't work on index.html
and 2nd query is how to fix the Uncaught ReferenceError
problem on index.js
My electron version is v8.2.0 and node version is v12.16.1 and dependencies on package.json
are as follows:
"dependencies": {
"request": "^2.88.2",
"require": "^2.4.20"
}
Anyone help me please. Thanks in advance.
Upvotes: 1
Views: 7113
Reputation: 1255
Since Electron 5, Node integration in the renderer process is disabled by default. To get around that, you need to declare nodeIntegration: true
when instantiating your BrowserWindow
.
// In the main process.
const { BrowserWindow } = require('electron')
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
})
Edit: As of Electron 12, you'll also need to define contextIsolation: false
in order to do this, as the default value of the flag has changed.
https://www.electronjs.org/docs/breaking-changes#default-changed-contextisolation-defaults-to-true
Upvotes: 13
Reputation: 94
The reason why require ('index.js');
doesn't work in the script tag is because require
isn't defined for the browser. It is only defined for Node. The reason why you are getting the ReferenceError
in index.js is because what <script src="index.js>
is actually doing is running the code in index.js in the browser environment. So since it is being run in the browser require
isn't defined here also.
Upvotes: 1