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")
Related
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.
First of all, I know that this is a question only a beginner would ask, but after going through more than 50 different solutions, uninstalling npm and installing yarn I have to ask this incredible dumb question.
Why doesnt this work?
I want to implement a simple titlebar using ElectronJS, the problem that I have is that the buttons (Close / Minimize / Maximize) do not work. The errors that I receive are the following:
The minimize error: titlebar.js:16 Uncaught TypeError: Cannot read property 'BrowserWindow' of undefined at HTMLButtonElement.maximizeApp (titlebar.js:16)
The maximize error: titlebar.js:16 Uncaught TypeError: Cannot read property 'BrowserWindow' of undefined at HTMLButtonElement.maximizeApp (titlebar.js:16)
The quit error: titlebar.js:21 Uncaught TypeError: Cannot read property 'getCurrentWindow' of undefined at HTMLButtonElement.quitApp (titlebar.js:21)
The JavaScript file that I use to control this is called titlebar.js. This is it:
const remote_v = require("electron").remote;
var minimize_v = document.getElementById("minimize");
var maximize_v = document.getElementById("maximize");
var quit_v = document.getElementById("quit");
minimize_v.addEventListener("click",minimizeApp);
maximize_v.addEventListener("click",maximizeApp);
quit_v.addEventListener("click",quitApp);
function minimizeApp(){
remote_v.BrowserWindow.getFocusedWindow().minimize();
}
function maximizeApp(){
remote_v.BrowserWindow.getFocusedWindow().maximize();
}
function quitApp(){
remote_v.getCurrentWindow().close();
}
Since many of the fixes for other problems like this is in the render process, this is the HTML File:
<!DOCTYPE html>
<head>
<title>Visionizer</title>
<link rel="stylesheet" href="css/editor.css">
<link rel="stylesheet" href="css/titlebar.css" >
</head>
<body>
<div class="container">
<div class="titlebar titlebarStyle">
<div class="windowTitle"> Visionizer </div>
<div class="windowControls windowControlsStyle">
<button id="minimize">-</button>
<button id="maximize">[]</button>
<button id="quit">x</button>
</div>
</div>
<div class="editorScreen">
</div>
</div>
<script src="js/titlebar.js"></script>
</body>
</html>
The weird thing about this is that, after much trying, I decided to copy the code from the tutorial from github, I thought that there may have been an error in my code that I was too dumb to see. It still didn't run. I uninstalled the package with npm and installed it with yarn using yarn global add electron#latest since some people suggested this.
I do not know whether this is important at all, but I will also copy my code from the main.js-file below since I want to be sure that I included everything:
const { app, BrowserWindow } = require('electron')
function createWindow () {
const win = new BrowserWindow({
width: 900,
height: 800,
minHeight: 650,
minWidth: 600,
frame: false,
webPreferences: {
nodeIntegration: true
}
})
win.loadFile('editor.html')
win.webContents.openDevTools()
}
app.whenReady().then(createWindow)
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
And here is the package.json file:
{
"dependencies": {
"electron": "^11.0.2"
},
"name": "*******",
"version": "1.0.0",
"description": "**********",
"main": "main.js",
"scripts": {
"start": "electron ."
},
"author": "************",
"license": "MIT"
}
Some questions on the internet were answered by saying that the project was started wrongly, I followed their advice, I start my projects using the yarn start command
Thank you for reading through this.
It looks like your remote module is undefined.
You'd want to set enableRemoteModule: true in your main window's webPreferences, or better yet, scrap remote altogether and do these operations from the main process.
The remote module was disabled in Electron 10.
My electron app works as expected but it keeps on opening new windows when I run spectron test that tests for number of windows opened.
Electron version - v8.0.2 , "spectron": "^10.0.1" . I am not sure how to check exact version of spectron.
I am just running a small demo, below I will give code snippet
Note: I am running the spectron test pointing to .exe file generated by electron-packager.
Does Anyone have an idea what is the issue if possible how to solve it?
main.js
const { app, BrowserWindow } = require('electron')
function createWindow () {
let win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
})
win.loadFile('index.html')
}
app.whenReady().then(createWindow)
index.js
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>
test.js
const assert = require('assert');
const path = require('path');
const Application = require('spectron').Application;
const electronPath = require('electron');
const app = new Application({
path: 'C:/demoElectronApp/winx64/demoelectronapp-win32-x64/demoelectronapp.exe',
});
describe('client_settings_app', function () {
this.timeout(10000);
beforeEach(() => {
return app.start();
});
it('shows only one initial window', async () => {
const count = await app.client.getWindowCount();
return assert.equal(count, 1);
});
})
package.json
{
"name": "demoelectronapp",
"version": "1.0.0",
"description": "",
"main": "main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"electronpackage": "electron-packager . --out winx64"
},
"author": "",
"license": "ISC",
"dependencies": {
"path": "^0.12.7"
},
"devDependencies": {
"electron": "^8.2.2",
"electron-packager": "^14.2.1",
"assert": "^2.0.0",
"mocha": "^7.1.1",
"spectron": "^10.0.1"
}
}
Okay, I was having the same issue. And solved by setting remote debugging port.
chromeDriverArgs: ['remote-debugging-port=9222']
Full test code:
const Application = require('spectron').Application
const assert = require('assert')
const electronPath = require('electron') // Require Electron from the binaries included in node_modules.
const path = require('path')
describe('Application launch', function () {
this.timeout(10000)
beforeEach(function () {
this.app = new Application({
// Your electron path can be any binary
// i.e for OSX an example path could be '/Applications/MyApp.app/Contents/MacOS/MyApp'
// But for the sake of the example we fetch it from our node_modules.
path: path.join(__dirname, '..', 'node_modules', '.bin', 'electron' + (process.platform === 'win32' ? '.cmd' : '')),
// Assuming you have the following directory structure
// |__ my project
// |__ ...
// |__ main.js
// |__ package.json
// |__ index.html
// |__ ...
// |__ test
// |__ spec.js <- You are here! ~ Well you should be.
// The following line tells spectron to look and use the main.js file
// and the package.json located 1 level above.
args: [path.join(__dirname, '..')],
env: {
ELECTRON_ENABLE_LOGGING: true,
ELECTRON_ENABLE_STACK_DUMPING: true,
NODE_ENV: 'test'
},
waitTimeout: 10e3,
requireName: 'electronRequire',
chromeDriverLogPath: '../chromedriverlog.txt',
chromeDriverArgs: ['remote-debugging-port=9222']
})
return this.app.start()
})
afterEach(function () {
if (this.app && this.app.isRunning()) {
return this.app.stop()
}
})
it('shows an initial window', function () {
return this.app.client.getWindowCount().then(function (count) {
assert.equal(count, 1)
// Please note that getWindowCount() will return 2 if `dev tools` are opened.
// assert.equal(count, 2)
})
})
})
I was having a similar issue, and changed the version of the packages I was working with.
This page has the version map:
https://github.com/electron-userland/spectron#version-map
It seems like this isn't your problem byt may help others.
I FINALLY found a way to fix this that worked for me. I found it in a comment by #wburgess-invision on this gitHub thread here: https://github.com/electron-userland/spectron/issues/60
Navigate to node_modules -> spectron -> lib -> launcher.js
after the line "const args = appArgs.concat(chromeArgs);" add a new line and copy and paste this: args.splice(args.indexOf('--enable-logging'), 1)
npm run build
To quote the thread: "I noticed that it was happening because of the --enable-logging parameter being passed in. So I made a modified version of launcher.js which purposely didn't include --enable-logging and it worked fine for us. I couldn't find where the spectron launcher was managing to pick up the --enable-logging flag from as I thought a better solution would have been just not providing it to launcher.js in the first place but I couldn't find out so I just went with the solution that worked for now. My assumption was that the --enable-logging flag was being picked up somewhere inside of webdriverio when the client is initialized and thus calls launcher.bat but I couldn't find out where."
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:
I have seen other questions about this but it is not the same.
Windows 7 x64
Node 6.6.0
electron 1.4.1
npm 3.19.8
My problem is that if I run npm start which calls electron . defined in my package.json the app runs fine. However if I just try to run electron . then I get the above error "Cannot find module app"
I think it must be path related but I can't figure it out. npm start is running the same command, I am running both commands in the root folder where main.js is located. I have also tried explicitly calling electron main.js with the same error.
Another note: when I run a debug session using Phpstorm it runs successfully. The debug configuration, Node interpreter = electron.cmd and Javascript File = main.js
package.json as requested
{
"name": "demoelectronaureliamongodb",
"title": "Demo Electron ES6, Aurelia MongoDB",
"version": "1.0.0",
"description": "Thick client demo app showing Electron, ES6, Aurelia, and MongoDB working together.",
"main": "main.js",
"scripts": {
"start": "electron .",
"build-mac": "electron-packager . 'DemoElectronAureliaMongoDB' --platform=darwin --arch=x64 --version=0.35.1 --overwrite --out ./build/mac",
"build-win": "electron-packager . 'DemoElectronAureliaMongoDB' --platform=win32 --arch=ia32 --version=0.35.1 --overwrite --out ./build/win"
},
"author": "",
"homepage": "http://karlshifflett.wordpress.com",
"license": "MIT",
"keywords": [
"electron",
"aurelia",
"es6",
"mongodb"
],
"repository": {
"type": "git",
"url": "https://github.com/Oceanware/demoelectronaureliamongodb.git"
},
"devDependencies": {
"electron-packager": "^5.1.1",
"electron-prebuilt": "^0.35.1"
},
"jspm": {
"directories": {
"baseURL": "src"
},
"dependencies": {
"aurelia-bootstrapper": "npm:aurelia-bootstrapper#^1.0.0-beta.1",
"aurelia-framework": "npm:aurelia-framework#^1.0.0-beta.1.0.2",
"font-awesome": "npm:font-awesome#^4.4.0"
},
"devDependencies": {
"babel": "npm:babel-core#^5.8.24",
"babel-runtime": "npm:babel-runtime#^5.8.24",
"core-js": "npm:core-js#^1.1.4"
}
}
}
main.js
(function () {
/**
* Main Electron process
*/
'use strict';
const electron = require('electron')
// Module to control application life.
const app = electron.app
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow
// var app = require('app');
// var BrowserWindow = require('browser-window');
var applicationMenu = require('./browser/application-menu');
var mainWindow = null;
app.on('ready', function () {
global.aureliaRoot = __dirname + '/src/';
applicationMenu.setup();
mainWindow = new BrowserWindow({
width: 900,
height: 700,
"min-width": 400,
"min-height": 300,
center: true,
resizable: true
});
mainWindow.loadUrl('file://' + __dirname + '/src/index.html');
});
})();
I did the below change to fix the issue:
const {app,BrowserWindow} =require('electron')
app.on('ready',function(){
var mainWindow= new BrowserWindow({
height:600,
width:600
})
})