I followed the suggestions in the answers of related questions, i.e. specifying
webPreferences: {
plugins: true
}
as part of the options when creating the BrowserWindow instance, but it is simply not working. Whenever I try to load/open/view a PDF file in electron, all I get is what looks like an empty/broken chromium PDF viewer like on this screenshot:
My electron version is "^13.1.2" according to my package.json and this is my main.js
// 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 win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
plugins: true
}
});
// and load the index.html of the app.
win.loadFile('test.pdf');
}
app.whenReady().then(() => {
createWindow()
})
app.on('window-all-closed', function () {
app.quit()
})
Can anyone tell me what I'm doing wrong?
An upgrade of electron helped me. i switched from 13.x to 16.x and it works now
Use PDFWindow package
`//main.js
app.on('ready', () => {
const win = new PDFWindow({
width: 800,
height: 600
})
win.loadURL('test.pdf')
})
//package.json
"dependencies": {
"electron-pdf-window": "^1.0.12",
},
`
Related
I'm making a desktop app using Vue CLI and vue-cli-plugin-electron-builder.
I need to use multiple renderer processes to do calculations, and I tried to initiate multiple BrowserWindows in the background.js file.
The background.js file is like this:
async function createWindow() {
// Create the main browser window.
win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
// Use pluginOptions.nodeIntegration, leave this alone
// See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION,
preload: path.join(__dirname, 'preload.js')
}
})
if (process.env.WEBPACK_DEV_SERVER_URL) {
// Load the url of the dev server if in development mode
await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
if (!process.env.IS_TEST) win.webContents.openDevTools()
} else {
createProtocol('app')
// Load the index.html when not in development
win.loadURL('app://./index.html')
}
// The worker process is a renderer BrowserWindow.
const worker_process = new BrowserWindow({
show: true,
width: 1440,
height: 900,
webPreferences: {
nodeIntegration: true,
webSecurity: false,
}
})
worker_process.loadFile(path.join(__dirname, 'work.html')) // THIS line doesn't work.
...
app.on('ready', async () => {
createWindow()
})
When I ran npm run electron:serve, the "main browser window" and the "worker process" both opened up, but the "worker process" didn't load the html file. The terminal showed:
Failed to load URL: file:///D:/dev2/dist_electron/work.html with error: ERR_FILE_NOT_FOUND''
I've already had ./src/worker.html file. I seemed that vue CLI or electron didn't copy this html file into the 'distribution folder'.
I tried to change
worker_process.loadFile(path.join(__dirname, 'work.html'))
to
worker_process.loadURL('app://./work.html')
and this popped up
OS warning.
I also tried adding the following into vue.config.js. This adding only gave me more errors in compiling.
module.exports = defineConfig({
pages:{
worker: './src/preload.js',
workers1: './src/preload2.js',
},
...
})
Any suggestion is appreciated! I can also provide more information.
My app does not display a window when it's built, but works fine when I run npm run serve
There is still an process running in task manager, and the same thing happens if I use the installer. I don't get any errors warnings from electron-builder.
background.js:
import { app, protocol, dialog, BrowserWindow, ipcMain, shell } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer'
import path from 'path'
import fs from 'fs'
import childProcess from 'child_process'
import ncp from 'ncp'
const isDevelopment = process.env.NODE_ENV !== 'production'
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let win
// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
{ scheme: 'app', privileges: { secure: true, standard: true } }
])
function createWindow () {
// Create the browser window.
win = new BrowserWindow({
width: 1200,
height: 600,
resizable: false,
maximizable: false,
frame: false,
webPreferences: {
// Use pluginOptions.nodeIntegration, leave this alone
// See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
preload: path.join(__dirname, 'preload.js')
}
})
if (process.env.WEBPACK_DEV_SERVER_URL) {
// Load the url of the dev server if in development mode
win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
if (!process.env.IS_TEST) win.webContents.openDevTools()
} else {
createProtocol('app')
// Load the index.html when not in development
win.loadURL(path.join(__dirname,'index.html'))
}
win.on('closed', () => {
win = null
})
}
// Quit when all windows are closed.
app.on('window-all-closed', () => {
// On macOS it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (win === null) {
createWindow()
}
})
I tried the fixes here and here to no avail.
I'm using electron-vue. You can find the full code here if you need more context
The issue ended up being code present inside of the app.on('ready') function. Any additional code needs to be written after the window is created, or the issue occurs.
My question is because I have been seeing how to do it for a long time and the first few times it worked, but lately I have had many problems.
I have seen several Blogs on how to link Electron with Angular but it always happens to me that I have errors with the main.js in the loadURL
const { app, BrowserWindow } = require('electron');
const url = require("url");
const path = require("path");
let mainWindow;
function createWindow() {
mainWindow = new BrowserWindow({
width: 800,
height: 600,
title: 'frontend',
backgroundColor: '#ffffff',
webPreferences: {
nodeIntegration: true
}
});
mainWindow.maximize();
mainWindow.webContents.openDevTools();
mainWindow.loadURL(
url.format({
pathname: path.join(__dirname, `/dist/index.html`),
protocol: "file:",
slashes: true
})
);
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();
})
I have already made the changes that videos and pages usually say about this as
Editing the package.json with "main": "main.js",
Put the dot in <base href ="./">
In angular.json projects> appName> architect> build> options> outputPath change it to "outputPath":"dist", without the project title
All of the above works until the time of packaging.
For what several mention using "electron-packager":"^14.2.1",
From a simpler command like
"packager": "electron-packager. --platform = win32 --out dist / --overwrite"
Where first of all, it generates an error with pathname: path.join (__ dirname, 'dist / index.html'), because it locates it somewhere else and I have to change dist / for src /
What the exe generates but at the moment of starting only the <app-root> </app-root> tag appears without the angular scripts, that is, an empty page
And others post to create the package.json script like:
"electron-package": "ng build --prod && electron-packager. --no-prune --ignore=/node_modules --ignore=/e2e --ignore=/src --overwrite"
or
"electron-package": "ng build --prod --base-href ./ && electron-packager. --no-prune --ignore=/e2e --ignore=/src --overwrite"
That the latter I think does not generate the index.html: c
Does anyone know a Definitive process with Anglar-cli and Electron?
I am creating an inventory application with the backend written in Python 3.7. I am using Electron to build a GUI for it and the Node.js Module "python-shell" to be able to communicate with the Python code. I would like for all of the code for python-shell to be in a separate JavaScript file (connector.js). If I run just that file with node from the command line it works perfectly fine, but calling the function from an HTML Button doesn't work.
I know that with one of the last updates to Electron nodeIntegration by default is false, but I did set that to true. Unfortunately it still doesn't allow me to communicate with the Node module within the Electron renderer process. If I copy the connector.js code into the main.js file used by Electron and call it on start of the application, it does work but calling it using an HTML button also obviously doesn't work.
This is the main.js file for Electron with nodeIntegration set to true.
const {app, BrowserWindow, Menu} = require('electron')
const fs = require('fs')
let mainWindow
function createWindow() {
mainWindow = new BrowserWindow({
// Set fixed size of main window
width: 1280,
height: 768,
resizable: false,
webPrefrences: {
nodeIntegration: true,
}
})
mainWindow.loadFile('./main.html')
mainWindow.on('closed', function () {
mainWindow = null
})
//Opens the dev tools by default.
mainWindow.webContents.openDevTools();
}
// Disable the default Menu Bar
Menu.setApplicationMenu(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()
})
And this is the connector.js file that calls the Python script with the correct arguments. functionality.py is for testing a very simple script that takes the first commandline argument (in this case addNewDataset) to call a function and the second as the name of a file it creates.
const {PythonShell} = require('python-shell')
var options = {
mode: 'text',
encoding: 'utf8',
pythonPath: 'python3',
pythonOptions: ['-u'],
scriptPath: './',
args: ['addNewDataset', 'testDataset123']
};
function test() {
PythonShell.run('functionality.py', options, function (err) {
if (err) throw err;
console.log('done');
});
}
It is loaded into the HTML file using a simple script tag
<script src="connector.js"></script>
and called using an input
<input type="submit" value="Button" onclick="test()">
I am pretty sure that I am just misunderstanding the way Electron and the main and renderer processes work. Unfortunately no matter what I look for on the Internet I don't seem to be able to get a solution that actually works.
Add a module.exports to your python file. It'll look like this:
module.exports = {
test: function () {
PythonShell.run('functionality.py', options, function (err) {
if (err) throw err;
console.log('done');
});
}
}
That above code will expose your function when you require the html file as a variable. Like this in the html file:
<HTML>
<input id="SpecialButton" type="submit" value="Button" onclick="test()">
<!-- ^add an id to the button -->
<script>
const python = require('python-file-path')
document.getElementById('SpecialButton').onclick = () => {
python.test() //call the function of the python file like this
}
</script>
</HTML>
I haven't tested my code in a IDE so I apologize for any syntax errors.
More about exporting functions in modules: In Node.js, how do I "include" functions from my other files?
Electron freezes when node-opcua is required in index.html and a process called Electron Helper takes up 100% of the cpu.
I have encountered the problem on macOS 10.14.2, but a friend tested in Windows 10 and that worked.
From package.json
"devDependencies": {
"electron": "^4.0.4"
},
"dependencies": {
"node-opcua": "^0.5.6"
}
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')
win.webContents.openDevTools()
}
app.on('ready', createWindow)
Index.html
<script>
// Does not work
const opcua = require('node-opcua')
console.log(opcua)
// Works
// const fs = require('fs')
// console.log(fs)
</script>
When running the simple code it should just print the opcua object in the console. But the complete electorn process freezes.
Solved it by updating node-opcua to 2.1.9 and electron to 6.0.11