How to receive data in Electron app from protocol link - javascript

I'm making a game client and I have it where you can launch the game from the browser like 'mygame://whatever'. I'm doing some debugging and I want it to show 'Received this data: whatever'. It does launch the app but it just shows undefined in the data box. How do I fix this?
main.js:
const {app, BrowserWindow} = require('electron');
let mainWindow;
function createWindow () {
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
})
mainWindow.loadFile('index.html');
}
app.on('ready', createWindow);
var link;
app.on('open-url', function (event, data) {
event.preventDefault();
link = data;
});
app.setAsDefaultProtocolClient('mygame');
// Export so you can access it from the renderer thread
module.exports.getLink = () => link;
index.html:
<!DOCTYPE html>
<html>
<body>
<p>Received this data <input id="data"></p>
<script>
const {getLink} = require('electron').remote.require('./main.js');
document.querySelector('#data').value = getLink();
</script>
</body>
</html>
package.json:
{
"name": "mygame",
"version": "1.0.0-dev",
"description": "Development copy.",
"main": "main.js",
"scripts": {
"start": "electron .",
"dist": "electron-builder"
},
"author": "Me",
"build": {
"protocols": {
"name": "mygame-protocol",
"schemes": [
"mygame"
]
}
},
"devDependencies": {
"electron": "^6.0.9",
"electron-builder": "^21.2.0"
}
}
All help is appreciated!

this code work only for iOS
app.on('open-url', function (event, data) {
event.preventDefault();
link = data;
});
In win32 you must use that code
process.argv[1]
so you can add that code in createWindow() like that:
function createWindow () {
// Crea la finestra del browser
let win = new BrowserWindow({
width: 800,
height: 600,
});
//other stuff
link = process.argv[1];
}
Resources that might be useful
electron url scheme “open-url” event

Related

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

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,
},
});

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 js button click not working

I'm working on an Electron-based application, and I don't have much experience with it or JavaScript or Node.js. Currently, I just want to open a window dialoge by a click on a button. But when i click the button nothing happens.
This is my package.json:
{
"name": "Routingtable_Splitter",
"version": "1.0.0",
"description": "...",
"main": "main.js",
"scripts": {
"start": "electron .",
"pack": "build --dir",
"dist": "build",
"package-win": "electron-packager . Splitter --overwrite --asar=true --platform=win32 --arch=ia32"
},
"build": {
"win": {
"target": "squirrel",
"icon": "build/icon.ico"
}
},
"author": "Robert Malleschitz",
"license": "ISC",
"devDependencies": {
"dialog": "^0.3.1",
"document": "^0.4.7",
"electron": "^2.0.4",
"electron-builder": "^20.19.1",
"electron-packager": "^12.1.0",
"electron-winstaller": "^2.6.4",
"fs": "0.0.1-security",
"remote": "^0.2.6"
},
"dependencies": {}
}
this is my HTML code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Tool</title>
</head>
<body>
<h1>Routingtable Splitter</h1>
<main>
<div>
<div style="text-align:right;">
<input type="text" placeholder="Bitte Routingtabelle laden" style="width: 260px" id="actual-file"/>
<input type="submit" value="Routingtabelle laden" id="load-file"/>
<br><br>
<textarea id="editor" style="width: 400px; height: 300px;"></textarea><br />
<input type="button" id="splitTable" value="Split" />
</div>
</div>
</main>
</body>
<script src="renderer.js"></script>
</html>
this is my main.js:
const {app, BrowserWindow} = require('electron')
const {Menu} = require('electron')
const {dialog} = require('electron')
const {remote} = require('electron')
const {document} = require('electron')
const {ipcMain} = require('electron')
var path = require('path')
var electronInstaller = require('electron-winstaller')
let win = null;
function createWindow () {
win = new BrowserWindow({
width: 1200,
height: 1000,
})
win.loadFile('index.html')
}
const menuTemplate = [
{
label: 'Datei',
submenu: [
{
label: 'Lade', click: () => {getRoutingTable();}
},
{
label: 'Beenden', click: () => {app.quit();}
}
]
}
];
function getRoutingTable(){
dialog.showOpenDialog(
{
defaultPath: 'c./',
filters: [
{ name: 'Text Files', extensions: ['txt'] }
],
properties:['openFile']
})
}
const menu = Menu.buildFromTemplate(menuTemplate);
Menu.setApplicationMenu(menu);
app.on('ready', createWindow)
{
console.log('app')
}
ipcMain.on('ldFileBtn', function (event, arg) {
console.log('ipcMain');
getRoutingTable();
event.sender.send("btnclick-task-finished", "yes");
});
This is my renderer.js:
const ipcRen = require('electron').ipcRenderer;
const ldFileBtn = document.getElementById('load-file');
ldFileBtn.addEventlistener('click', function() {
console.log('btn_click')
var arg = 'secondparam';
ipcRen.send('ldFileBtn', arg);
});
Why won't the button work? I hope someone can help me. Thanks in advance.

How to change native menu of electron-quick-start example app

The electron app open with the same default menu that appear in the electron-quick-start example app and how to change it?
Also tried the menu example on the docs but nothing changes.
when I hide the menu with mainWindow.setMenu(null); the menu is gone but still can't init the new menu
any ideas?
platform: windows 7
electron ver: 0.36.4
ref files:
package.json:
{
"name": "electric_timer",
"version": "0.1.0",
"description": "a Time sheet & project managment",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "none"
},
"author": "Eyal Ron",
"license": "MIT"
}
app.js:
var app = require('app');
var BrowserWindow = require('browser-window');
app.on('ready', function (){
var mainWindow = new BrowserWindow({
width: 800,
height: 600
});
mainWindow.setMenu(null);
mainWindow.loadUrl('file://' + __dirname + '/main.html');
});
main.js:
var remote = require('remote');
var Menu = remote.require('menu');
var menu = Menu.buildFromTemplate([
{
label: 'Electron',
submenu: [
{
label: 'Prefs',
click: function(){
alert('hello menu');
}
}
]
}
]);
Menu.setApplicationMenu(menu);
main.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>electron test</title>
</head>
<body>
<h1>hello world</h1>
<script>requier('./main.js')</script>
</body>
</html>
Electron's 'default_app' sets the menu; if you want to avoid this, you need Electron to start your app directly not via the default app (note: if you start your app with something like electron . you actually start the default app).
Electron looks in its resource folder for 'app', 'app.asar' or 'default_app', so in order to start your app directly you need to either copy or link it into Electron's resource folder.
Regardless of how you start your app, you can set your menu using Menu.setApplicationMenu -- you can do it in the main process, you don't need to do it in the Renderer like in your example. Incidentally, there is a typo in your main.html (requier instead of require) so if that's your actual code it would indicate that your main.js does not run at all.
Put your logic to customise the menu into your app('ready') event callback. Give try to following code example
const {app, BrowserWindow, Menu} = require('electron');
let mainWindow;
let menuTemplate = [
{
label: "Window Manager",
submenu: [
{ label: "create New" }
]
},
{
label : "View",
submenu : [
{ role : "reload" },
{ label : "custom reload" }
]
}
];
function appInit () {
// Create the browser window.
mainWindow = new BrowserWindow({width: 800, height: 600})
// and load the main.html of the app.
mainWindow.loadFile('main.html')
let menu = Menu.buildFromTemplate(menuTemplate);
Menu.setApplicationMenu(menu);
}
app.on('ready', () => {
appInit();
})
It looks like the electron Menu and MenuItem objects are set up to be immutable.
This means if you want to modify them, you have to create new objects and use that instead. This is what my code does for this, to hide the help menu and developer tools:
// main.js
function createWindow () {
// Create the browser window.
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
...
let defaultMenu = Menu.getApplicationMenu()
let newMenu = new Menu();
defaultMenu.items
.filter(x => x.role != 'help')
.forEach(x => {
if(x.role == 'viewmenu' && process.env.NODE_ENV == 'production') {
let newSubmenu = new Menu();
x.submenu.items.filter(y => y.role != 'toggledevtools').forEach(y => newSubmenu.append(y));
x.submenu = newSubmenu;
newMenu.append(
new MenuItem({
type: x.type,
label: x.label,
submenu: newSubmenu
})
);
} else {
newMenu.append(x);
}
})
Menu.setApplicationMenu(newMenu);
...
})
}
app.on('ready', createWindow)
Where is Electron in your app? Your package.json file should look like this:
{
"name": "todos",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"electron": "electron ."
},
"author":
"Who Cares <email#example.com> (https://doesntmatter.com/)",
"license": "MIT",
"dependencies": {
"electron": "3.0.8"
}
}
Your Electron side will look like this:
const electron = require('electron');
const { app, BrowserWindow, Menu } = electron;
let mainWindow;
app.on('ready', () => {
mainWindow = new BrowserWindow({});
mainWindow.loadURL(`file://${__dirname}/main.html`);
const mainMenu = Menu.buildFromTemplate(menuTemplate);
Menu.setApplicationMenu(mainMenu);
});
const menuTemplate = [
{
label: 'File'
}
];
Even with fixing up the syntax you will still run into the problem of having taken over the default Electron menu and its key binds. You are saying you are going to add your own custom menu and keybinds, which in production if that is your goal then fine, but it sounds like you have lost functionality that you want to maintain.
You could fix it like this:
const menuTemplate = [
{
label: 'File',
submenu: [{ label: 'New Todo' }]
}
];

Categories

Resources