alert(__dirname) not producing any output in an electron app - javascript

I do not get the desired output when running the following electron app i.e alert box containing pwd as output. However, the commented line inside index.html seems to work fine. The developer console of the chromium window says "Uncaught ReferenceError: __dirname is not defined at HTMLButtonElement.<anonymous>". This snippet is taken verbatim(except the commented line) from the book "Electron in action" by Steve Kinney 2019 edition.
any suggestions?
package.json is as follows
{
"name": "bookmarker",
"version": "1.0.0",
"description": "electron app",
"main": "./app/main.js",
"scripts": {
"start": "electron .",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Wasim Aftab",
"license": "ISC",
"dependencies": {
"electron": "^9.0.0"
}
}
main.js is as follows
const {app, BrowserWindow} = require('electron');
let mainWindow = null;
app.on ('ready', () => {
console.log('Hello, from electron');
mainWindow = new BrowserWindow();
mainWindow.webContents.loadFile(__dirname + '/index.html');
});
index.html is as follows
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Security-Policy" content="
default-src 'self';
script-src 'self' 'unsafe-inline';
connect-src *">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Bookmarker</title>
</head>
<body>
<h1>Hello from Electron</h1>
<p>
<button class="alert">Current Directory</button>
</p>
</body>
<script>
const button = document.querySelector('.alert');
button.addEventListener('click', () => {
alert(__dirname);
// alert(window.location.pathname.replace(/[^\\\/]*$/, ''));
});
</script>
</html>

__dirname is a nodejs concept, it does not exist in the browser.
One way to resolve the issue is to set nodeIntegration to true:
mainWindow = new BrowserWindow({
webPreferences: {
nodeIntegration: true
}
});
Another way would be to use a preload script (nodeIntegration is always enabled for preload scripts):
mainWindow = new BrowserWindow({
webPreferences: {
preload: (__dirname + "/preload.js")
}
});
And then in the preload.js file:
window.__dirname = __dirname

For electron v16.0.4, addition of contextIsolation: false also required
$ npx electron --version
v16.0.4
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
// enableRemoteModule: true,
},
});

Related

imported library function not defined from JavaScript webpack export

so I was following this https://webpack.js.org/guides/author-libraries/ from the web pack documentation, my file is just slightly different. No matter how I try to do this, I get various problems.
in my src/index.js file I have a simple function for example.
const Dinero = require('dinero.js')
export function calculateGrossRev(hudmonthly){
// Calculates the yearly gross rev
const hudonebr = Dinero({amount: hudmonthly, currency: 'USD'})
.multiply(12);
return hudonebr.getAmount();
}
In my package.json file I have.
{
"name": "library",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "webpack",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"dinero": "^1.0.1",
"lodash": "^4.17.21",
"webpack": "^5.51.1",
"webpack-cli": "^4.8.0"
},
"dependencies": {
"dinero.js": "^1.9.0"
}
}
In my webpack config file I have.
const path = require('path');
module.exports = {
mode: "development",
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'dinero-calc.js',
library: {
name: "dineroNumbers",
type: "umd",
},
},
};
when I run "npm run build", I get the big bundled file, all looks well to me.
I then have an index.html file I run with Live Server in VScode.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TEST</title>
</head>
<h1>TEST</h1>
<script src="./dinero-calc.js"></script>
<script>
console.log(window.dineroNumbers.calculateGrossRev(8200));
</script>
<body>
</body>
</html>
With the simple example from the docs I'm able to get the expected output from their expected function printed to the console, however with my imported function it says
index.html:11 Uncaught TypeError: Cannot read property 'calculateGrossRev' of undefined at index.html:11
I think a problem is in the script source url <script src="./dinero-calc.js"></script>. Please, check paths of index.html and dinero-calc.js.
According to your script tag, they should be in the same directory under dist folder.
[Upd]
First, install dinero.js which used in src/index.js.
npm i dinero.js
Also, dinero should be placed in dependencies, not devDependencies, because dinero.js used in your code.
Second, call function like this
Dinero.default({
amount: hudmonthly,
currency: "USD",
}).multiply(12);

Electron nodeIntegration not working, also general weird Electron behavior [duplicate]

This question already has answers here:
Unable to use Node.js APIs in renderer process
(2 answers)
Closed 1 year ago.
I'm new to Electron, and I've really been struggling with getting it to work. I'm experiencing behavior I cannot explain, so here's a sum:
I cannot get the communication between Electron and the html to work
"Uncaught ReferenceError: require is not defined" inside the website, even though I have nodeIntegration:true
File Tree:
./
index.html
index.js
package-lock.json
package.json
node_modules/
index.js:
const electron = require("electron");
const Ffmpeg = require("fluent-ffmpeg");
const CmdExec = require('child_process');
const {
app,
BrowserWindow,
ipcMain
} = electron;
function createWindow() {
//If I put the main window ini into here, and then call app.on("ready", createWindow()); app says
//"Cant create window before ready", even though I just moved the funcion from inside ready to here..
}
app.on('ready', () => {
mainWindow = new BrowserWindow({
webPreferences: {
nodeIntegration: true
}
});
mainWindow.loadURL(`${__dirname}/index.html`);
});
ipcMain.on("video:submit", (event, path) =>{
CmdExec.exec("echo hello", (value)=>{console.log(value)});
});
html:
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="">
</head>
<body>
<h1>WELCOME!</h1>
<script src="" async defer></script>
<form action="">
<div>
<br>
<label for=""></label>
<input type="file" accept="video/*" name="" id="">
</div>
<button type="submit">get info</button>
</form>
<script>
const electron = require("electron");
electron.send('perform-action', args);
document.querySelector("form").addEventListener("submit", (event) => {
event.preventDefault();
const {path} = document.querySelector("input").files[0];
window.api.send("video:submit", path);
});
//Tried multiple methos Ive found on stackoverflow,, dont think I implemented them right
//though
</script>
</body>
</html>
package.json:
{
"name": "media_encoder",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"electron": "electron ."
},
"author": "",
"license": "ISC",
"dependencies": {
"electron": "^12.0.0"
}
}
Electron 12 is now defaulting contextIsolation to true, which disables Node (here are the release notes; and here's the PR).
Here's a discussion of this change. nodeIntegration for what it's worth is going to be removed in a future Electron version.
The easiest way to fix this is to simply disable context isolation:
mainWindow = new BrowserWindow({
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
That being said, you might want to consider keeping contextIsolation enabled for security reasons. See this document explaining why this feature bolsters the security of your application.

Cannot use require in a separate js file in Electron

I have a very simple Electron app, using version 5.0.1.
Here is my index.html file:
<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<title>Webgl</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/104/three.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<script src="./initialization.js"></script>
<link rel="stylesheet" type="text/css" href="application.css">
</head>
<body>
<script>
initialization();
</script>
</html>
Then my main.js file:
const {app, BrowserWindow} = require('electron')
const path = require('path')
const url = require('url')
let win
function createWindow () {
// Create the browser window.
win = new BrowserWindow({ width: 1280,
height: 720,
nodeIntegration: true,
resizable: false,
maximizable: false })
// and load the index.html of the app.
win.loadFile('index.html')
// Open the DevTools.
win.webContents.openDevTools()
// Emitted when the window is closed.
win.on('closed', () => {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
win = null
})
}
app.on('ready', createWindow)
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
if (win === null) {
createWindow()
}
})
my package.json file:
{
"name": "estimation",
"version": "1.0.0",
"description": "estimation app",
"main": "main.js",
"scripts": {
"start": "electron ."
},
"author": "",
"license": "ISC",
"devDependencies": {
"electron": "^5.0.1"
}
}
Then my inittialization.js file that contains the initialization() method and const fs = require('fs');
const fs = require('fs');
function initialization(){
}
Now I have asked the same question in multiple places, I have tried multiple solutions, nothing works. I am wondering if this is an Electron bug at this stage.
The error I can't get rid off and I keep getting whatever I do is this Uncaught ReferenceError: require is not defined
I simply want to use require in another JS file. Why is node.js or electron not picking this up ?
Place the nodeIntegration inside webPreferences attribute
{ width: 1280,
height: 720,
webPreferences : { nodeIntegration: true },
resizable: false,
maximizable: false
}

How to integrate trading view into electron

I wanted to build trading apps using electron JS and using the TradingView library but I got stuck on how to implement it. I also created a new blank project to implement it, but still result.
Is there anyone has ever implement TradingView to electron and could give me solution to this?
Blank app result
Error in console
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://demo_chart.tradingview.com/charting_library/charting_library.min.js"></script>
<script type="text/javascript" src="https://demo_chart.tradingview.com/datafeeds/udf/dist/polyfills.js"></script>
<script type="text/javascript" src="https://demo_chart.tradingview.com/datafeeds/udf/dist/bundle.js"></script>
<script type="text/javascript">
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
TradingView.onready(function()
{
var widget = window.tvWidget = new TradingView.widget({
// debug: true, // uncomment this line to see Library errors and warnings in the console
fullscreen: true,
symbol: 'AAPL',
interval: 'D',
container_id: "tv_chart_container",
// BEWARE: no trailing slash is expected in feed URL
datafeed: new Datafeeds.UDFCompatibleDatafeed("https://demo_feed.tradingview.com"),
library_path: "charting_library/",
locale: getParameterByName('lang') || "en",
disabled_features: ["use_localstorage_for_settings"],
enabled_features: ["study_templates"],
charts_storage_url: 'http://saveload.tradingview.com',
charts_storage_api_version: "1.1",
client_id: 'tradingview.com',
user_id: 'public_user_id',
theme: getParameterByName('theme'),
});
});
</script>
</head>
<body style="margin:0px;">
<div id="tv_chart_container"></div>
</body>
</html>
Never used electron so using this opportunity to try it out myself. This is the steps I took.
Look at the documentation https://electronjs.org/docs/tutorial/first-app
1) created a folder called electron-test
2) run command npm init in that folder
3) modify package.json to be this
{
"name": "electron-test",
"version": "1.0.0",
"description": "",
"main": "main.js",
"scripts": {
"start": "electron ."
},
"author": "",
"license": "ISC",
"dependencies": {}
}
4) create main.js
const { app, BrowserWindow } = require("electron");
function createWindow() {
// Create the browser window.
win = new BrowserWindow({ width: 800, height: 600 });
// and load the index.html of the app.
win.loadFile("index.html");
}
app.on("ready", createWindow);
5) create index.html
6) run command npm install electron
7) run command npm start
This is the result
Is there anyone has ever implement TradingView to electron and could give me solution to this?
Well I don't have solution to the error, but I have found my way out to build an tradingView+ElectronJs app.
In short, you can start with TradingView Charting Library Integration Examples, from which you can choose the kind of integration template to start with(I just use react-javascript to start my app).And I just take this template for example.
After follow How to start to configure the app properly. You should first install election to your app(which means run npm install --save electron in the directory root), then add the main.js to your directory root, and configure your package.json and main.js properly. Blow is my package.json and main.js code.
package.json
{
"name": "knownsec-fed",
"version": "0.1.0",
"private": true,
"main": "main.js", // 配置启动文件
"homepage":".", //
"dependencies": {
"electron": "^1.7.10",
"react": "^16.2.0",
"react-dom": "^16.2.0",
"react-scripts": "1.1.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject",
"electron-start": "electron ." // start electron app
}
}
main.js
const {app, BrowserWindow} = require('electron')
const path = require('path')
const url = require('url')
let mainWindow
function createWindow () {
mainWindow = new BrowserWindow({width: 800, height: 600})
/**
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}))
*/
mainWindow.loadURL('http://localhost:3000/');
// mainWindow.webContents.openDevTools()
mainWindow.on('closed', function () {
mainWindow = null
})
}
app.on('ready', createWindow)
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', function () {
if (mainWindow === null) {
createWindow()
}
})
to start the electron app, first run npm start to start react then run npm run electron-start to start electron app and then all thing done.
When you open Object with widget, your widget trying to find static folder from wrong path. Just connect library in widget option like this:

Electron not loading web application with full functionalities

I tried loading a web application in electron using window.loadurl and as webview in html. Application is displaying, but with different errors like:
$ jquery not defined
Uncaught TypeError: $(...).daterangepicker is not a function
Uncaught TypeError: Cannot read property 'getContext' of undefined
I tried different methods and finally get rid off '$ jquery not defined' error.
Why electron is not acting as a browser. This application is working fine on all browsers.
How can I load this web application to my electron with functionalities.
My web application is :
www.mcgeoautomation.com
My index.js file is:
const electron = require('electron');
const app = electron.app;
var path=require('path');
const BrowserWindow = electron.BrowserWindow;
var mainWindow;
app.on('ready',function(){
mainWindow = new BrowserWindow({
width: 1024,
height: 768,
backgroundColor: '#2e2c29',
show:false,
});
mainWindow.loadURL(`file://${__dirname}/webView.html`);
mainWindow.maximize(true);
// mainWindow.setMenu(null);
mainWindow.once('ready-to-show',()=>{
mainWindow.show()
})
mainWindow.on('close', (e)=>{
app.quit();
});
});
package.json file:
`{
"name": "crushmate",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "electron ."
},
"author": "",
"license": "ISC",
"dependencies": {
"electron": "^1.7.9",
"jquery": "^3.2.1"
},
"devDependencies": {
"electron-prebuilt": "^1.4.13"
}
}`
Please help...
Regards...
Electron doesn't handle jQuery the same as a regular browser does. You have to essentially inject it into the webview. Can't test this right now but should get you on the way to it working.
index.html
<!DOCTYPE html>
<html>
<head>
<title>jQuery injection into webview preload</title>
</head>
<body style="overflow:hidden;">
<webview id="webview" preload="./preload.js" src="http://www.mcgeoautomation.com" style="position:absolute;width:100%;height:100%;"></webview>
<script>
// need to have a script tag make webview work even if you don't plan to use it...
</script>
</body>
</html>
preload.js
window.onload = function() {
var script = document.createElement("script");
script.src = "https://code.jquery.com/jquery-2.1.4.min.js";
document.body.appendChild(script);
};
I ran into the same issue and deativating nodeIntegration solved it for me.
Just add following code when creating a BrowserWindow:
webPreferences: {
nodeIntegration: false
}
(The used electron version is "11.2.0")

Categories

Resources