Import libraries in Angular-Electron project - node.js

I'm developing a web application using Angular 5.
I have wrapped it inside Electron because of I need to use the filesystem.
In order to use the node features I set the main.js file as follows:
mainWindow = new BrowserWindow({
width: 1280,
height: 800,
backgroundColor: '#ffffff',
webPreferences: {
nodeIntegration: true
}
})
As you can see nodeIntegration is set to true.
With this configuration everything works well but I noticed that when I import some library in the .angular-cli.json file that libraries are not imported.
For example I import toastr as follows: (.angular-cli.json file)
"scripts": [
"../node_modules/jquery/dist/jquery.min.js",
"../node_modules/bootstrap/dist/js/bootstrap.bundle.min.js",
"../node_modules/toastr/build/toastr.min.js"
],
On the browser it works like a sharm, but in Electron I get this error:
Uncaught (in promise): ReferenceError: toastr is not defined
ReferenceError: toastr is not defined ...
How should I import an external library in order to make it works in Electron && Browser?
Thanks a lot

Related

Electron contextBridge works on desktop but not on web

My stack consist of Electron, React, FastAPI. I created a contextBridge in the preload.js file. Everything is working fine on the desktop application however when I am on the web, I get the following error below. If anyone knows what might be the cause of this please let me know where to start looking! I don't fully understand why it's a type error. Thank you!
preload.js
const { contextBridge, ipcRenderer } = require("electron");
contextBridge.exposeInMainWorld("api", {
rollDice: async () => {
return await ipcRenderer.invoke("roll-dice");
},
});
error in the browser console
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'rollDice')
You can recreate the bug by following this:
npx create-react-app my-app --template electron-python-fastapi
cd my-app
python -m pip install virtualenv
python -m virtualenv venv
.\venv\Scripts\activate
python -m pip install -r requirements.txt
npm start
Edit: in my App.js file window.api seems to be undefined. Any reason that might be the case for Web but not Desktop?
Edit: I added console.log("running preload"); at the end of my preload.js file and seems like it doesn't preload the file when running on the browser(web).
electron.js
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
enableRemoteModule: false,
preload: path.join(__dirname, "preload.js"),
},
});

how to solve this error indexhtml :Uncaught ReferenceError: require is not defined in electron [duplicate]

This question already has answers here:
With contextIsolation = true, is it possible to use ipcRenderer?
(3 answers)
Closed 1 year ago.
> index.html:
As u can see in index.html code (const electron = require('electron');this require arise an error as require is not define i use window10.
<script>
const electron = require('electron');
const { ipcRenderer } = electron;
document.querySelector('form').addEventListener('submit',(event) =>{event.preventDefault();
event.preventDefault();
const file =document.querySelector('input').files[0];
});
</script>
> Main.js:
// Modules to control application life and create native browser window
const {app, BrowserWindow} = require('electron')
const path = require('path')
function createWindow () {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true, // is default value after Electron v5
contextIsolation: true, // protect against prototype pollution
enableRemoteModule: false, // turn off remote
preload: path.join(__dirname, "preload.js") // use a preload script
}
});
mainWindow.loadFile('index.html')
Electron is a package you should use in the nodejs environment, not in the browser. Also in the browser you can't use the require function, you should use instead the import and export syntax.
That because javascript is a script language meant to run in browsers, it doesn't make sense to require electron in your frontend script, but, since your serving your files through the electron service and not in a browser window you can access the require by calling the window.require('pckg') method, still doesn't make any sense to require electron in a client-side window tho, it's like if an express server renders a page that creates another server.
If you just want to create another window you should do that in the main electron file, in your case the Main.js file.

Jest check if setting is true or false

I want to make a simple jest test to check if devTools was left on for an Electron app. I have this function in main.js:
function createWindow () {
win = new BrowserWindow({
width: 1024,
height: 728,
backgroundColor: '#000000',
webPreferences: {
nodeIntegration: true,
devTools: false
},
frame: false
});
I just want to make a test to see if devTools is false. Can jest just read that specific variable?
Yes, you can access the options that were passed to the BrowserWindow constructor like such:
win = new BrowserWindow( {
webPreferences: {
nodeIntegration: true,
devTools: true
},
});
console.log( win.webContents.browserWindowOptions.webPreferences.devTools );
// will print true
Note that you can only retrieve the value if it actually appears in the constructor call options, otherwise it is undefined.
Further note that this is undocumented: the Electron docs do not mention webContents.browserWindowOptions. I have tried this using Electron 10.1.0.
I've recently found out about Spectron and it allows you to test Electron apps. Their documentation shows them using Mocha, but I'm pretty sure you can get it working with Jest. I don't need to check if devTools is on in my Electron app anymore, but I'm posting here for anyone that wants to do something similar.

Get path of associated file when opened on double click Electron builder

Information:
OS: windows 10
Electron Version: Latest
Electron Builder Version: Latest
I am trying to make an app that edits .txt files. I want to get the path of the text file when it is opened with the application (i.e. the user chooses to open the .txt with my app). I have included the following in the build of my package.json:
"fileAssociations": [
{
"name": "Text Files",
"description": "Plain Text File",
"ext": [
"txt"
]
}
],
This makes the application open with the file however how do I get the path of the file that was used to open the app. I know I have to do something with a process.argv however I have no idea how to use this. I have tried the below with no success:
ipcMain.on('get-file-data', function(event) {
var data = null;
if (process.platform == 'win32' && process.argv.length >= 2) {
var openFilePath = process.argv[1];
console.log(data)
win.webContents.send('openFile', openFilePath)
}
});
How can I get the path of the file?
This is the log of the whole process. As we can see here, the second argv is the path of the input file path. So process.argv[1] will be enough to the file path. Not sure why you can't get a path.
Maybe this comes from your ipc event listener. Which means the get-file-data is not fired correctly.
As you can see in this below image,I'm showing this process variable in this browser console. Here is how I exposed process variable to the renderer. But this is just for debug! Recommend not doing this in your production.
preload.js
process.once("loaded", () => {
window.process = process;
});
main.js
mainWindow = new BrowserWindow({
width: 1024,
height: 728,
minWidth: 800,
minHeight: 750,
webPreferences: {
enableRemoteModule: true,
preload: path.join(__dirname, "preload.js"),
}
});
And you can use window.process or process on your renderer
I managed to get the path with the following:
const { remote } = require('electron');
console.log(remote.process.argv[1])
This returns the path of the file used to open the app!

Requiring node modules in ionic + electron (5.0.0) desktop application

I'm building a desktop application using ionic and electron.
I started using electron v4.1.3 and i was able to require node modules in the "ionic part" of the application, for example in the home.ts file by using:
import { Component } from '#angular/core';
#Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
ngOnInit () {
console.log ((<any> window).require ("fs"));
}
}
and this is what i get:
As you can see i can access all fs methods, so i can read, write, copy files and whatever else.
Now i have installed electron v5.0.0, i created the same application but i get an error when i try to require fs module in the ngOnInit method:
window.require is not a function
How can i fix this? If you need more details on installation or envinronment just tell me, thank you!
nodeIntegration is now disabled by default in 5.0.0 as per breaking changes document.
https://github.com/electron/electron/blob/master/docs/api/breaking-changes.md#planned-breaking-api-changes-50
and the release notes
https://github.com/electron/electron/releases/tag/v5.0.0
So you need to enable it :
const mainWindow = new BrowserWindow({
webPreferences: { nodeIntegration: true }
});

Resources