import menu to browser window by "require" function - javascript

I am working on a electron demo by following this tutorial.
just wondering what happened in the require line of code.
./menu/mainmenu.js defines the menu items.
const {Menu} = require('electron')
const electron = require('electron')
const app = electron.app
const template = [
{
label: 'Edit',
submenu: [
{
role: 'undo'
},
{
role: 'redo'
},
{
type: 'separator'
},
{
role: 'cut'
},
{
role: 'copy'
},
{
role: 'paste'
},
{
role: 'pasteandmatchstyle'
},
{
role: 'delete'
},
{
role: 'selectall'
}
]
}
]
const menu = Menu.buildFromTemplate(template)
Menu.setApplicationMenu(menu)
main.js
const { app, BrowserWindow, ipcMain } = require('electron');
let win;
function createWindow () {
win = new BrowserWindow({
width: 880,
height: 660,
webPreferences: {
nodeIntegration: true
}
})
// and load the index.html of the app.
win.loadFile('index.html')
require('./menu/mainmenu') //does this line copied the whole mainmenu.js file?
}
does the require('./menu/mainmenu') copy whole file into main.js?
Or imported some modules? In the mainmenu.js file There is no export keyword.
according to the node.js documentation,
"The basic functionality of require is that it reads a JavaScript file, executes the file, and then proceeds to return the exports object."

require here doesn't copy file around (unlike c++ #include)
Instead it execute the file and return the exported items (if any)
Since there is no export in './menu/mainmenu' when you call require, it simply executed that file.
The problem with this approach is require would only process that file once*, the proper way is actually export something which can be used multiple times.
example:
./menu/mainmenu.js
//...
const menu = Menu.buildFromTemplate(template)
export default ()=>Menu.setApplicationMenu(menu)
main.js
const { app, BrowserWindow, ipcMain } = require('electron');
let win;
function createWindow () {
//...
const setmenu = require('./menu/mainmenu') // you can put this at top, too
setmenu();
// or you can execute it inline
// require('./menu/mainmenu')()
}
note: you may need https://www.npmjs.com/package/babel-plugin-add-module-exports or some workaround to make require and default export works together.
*the problem with this is you cannot really rely on it to work everytime, e.g. change menu from A -> B -> A , the second require('A') would silently do nothing.

Related

Import function only (not entire file stack) into Angular from vanilla JavaScript

The Challenge
I am working on an Electron/Angular app that will display an emergency message to multiple computers in the event of a tornado or other incident. To accomplish this, I am using a WebSocket protocol (Signral R) on the backend to send the alert, which then triggers Electron's main.js (running in the background) to launch a window on any devices running the app.
The arrival of the message triggers the window to launch, but I also need to use the message in the Angular part of the app (which does not initialize until after the window is open) to indicate the nature of the emergency. To avoid timing problems, I planned to import a function into my app.component.ts that would be called at ngOnInit to retrieve an emergency variable from main.js.
The Problem
Angular does not like the import from raw JavaScript. Intuitively you would think Angular would only import the exported class. However it appears to try and import Electron as well (generating a conflict with 'fs' and 'path' that is explained here), generating the following error message:
./node_modules/electron/index.js:1:11-24 - Error: Module not found: Error: Can't resolve 'fs' in 'C:\Users\me\electron-app\node_modules\electron'
./node_modules/electron/index.js:3:13-28 - Error: Module not found: Error: Can't resolve 'path' in 'C:\Users\me\electron-app\node_modules\electron'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "path": require.resolve("path-browserify") }'
- install 'path-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "path": false }
In spite of doing considerable research, I have not found anything approaching a solution. Any ideas for only importing the information I want would be much appreciated. Here are my files:
main.js (simplified somewhat)
const signalR = require("#microsoft/signalr")
const { app, shell, BrowserWindow, Menu, nativeImage, Tray } = require('electron')
const path = require("path");
const url = require("url");
//various setup logic goes here
//...
webSocketConnection.on("EmergencyActivation", (jsonData) => {
createElectronWindow();
const emergencyMessage = jsonData
});
module.exports = class Emergency {
getEmergency() {
return emergencyMessage
}
}
app.component.ts
import { Component, OnInit } from '#angular/core';
import { Emergency } from './../../main';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
constructor(private emergency: Emergency) {}
ngOnInit() {
console.log(this.emergency.getEmergency())
}
}
Though I do not use Angular, I think the issue is communication between your main process and your render process (or
lack
thereof).
Don't try to communicate between processes by importing from the main process to the render process (which can't
be done). Instead, use Inter-Process Communication.
IE: Once an emergency message has been received via webSocket, create the window and then send an IPC message to that newly
created window.
I have needed to "mock" your webSocketConnection functionality for the sake of the below example.
main.js (main process)
const electronApp = require('electron').app;
const electronBrowserWindow = require('electron').BrowserWindow;
const nodePath = require('path');
let window;
function createWindow() {
window = new electronBrowserWindow({
x: 0,
y: 0,
width: 800,
height: 600,
show: false,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
preload: nodePath.join(__dirname, 'preload.js')
}
});
window.loadFile('index.html')
.then(() => { window.show(); });
return window;
}
electronApp.on('ready', () => {
listenForEmergency();
});
electronApp.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
electronApp.quit();
}
});
electronApp.on('activate', () => {
if (electronBrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
// ---
// Mock of "webSocketConnection.on" function (for testing only)
function listenForEmergency() {
let message = 'Emergency: We have no beer'
console.log('Wait 5 seconds before "receiving" emergency message'); // Testing
setTimeout(() => { showEmergencyWindow(message); }, 5000);
}
// Create window and send message via IPC
function showEmergencyWindow(message) {
window = createWindow();
window.webContents.send('emergency', message); // <-- Use of IPC messaging
}
// Create window and send message via IPC
// webSocketConnection.on("EmergencyActivation", (jsonData) => {
// window = createWindow();
// window.webContents.send('emergency', jsonData); // <-- Use of IPC messaging
// });
preload.js (main process)
const contextBridge = require('electron').contextBridge;
const ipcRenderer = require('electron').ipcRenderer;
contextBridge.exposeInMainWorld(
'electronAPI', {
emergency: (message) => {
ipcRenderer.on('emergency', message)
}
});
index.html (render process)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Emergency</title>
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';"/>
</head>
<body>
<h1>Emergency</h1>
<div id="message"></div>
</body>
<script>
window.electronAPI.emergency((event, message) => {
document.getElementById('message').innerText = message;
})
</script>
</html>

vueHtml2Pdf renders blank page (Nuxt)

I am using vueHtml2Pdf to generate my page to pdf, but when I wrap my content inside VueHtml2pdf tag nothing renders on my page, but it downloads when I click the download button. (Nuxt)
methods: {
downloadPDF() {
this.$refs.html2Pdf.generatePdf()
},
},
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<ArticleActions #download="downloadPDF()" />
<client-only>
<vue-html2pdf
ref="html2Pdf"
:show-layout="false"
:enable-download="true"
:pdf-quality="2"
:manual-pagination="true"
pdf-content-width="100%"
:html-to-pdf-options="htmlToPdfOptions"
>
<section slot="pdf-content">
<!-- content -->
<div
v-interpolation="{ newWindow: true }"
class="articleContent__content"
v-html="article.content"
></div>
<!-- /content -->
</section>
</vue-html2pdf>
</client-only>
I have a working solution for Nuxtv3 (with server-side rendering). After trying a bunch of different vue-specific packages, including vue-html2pdf, I realized that most of them have been written for Vue2.
Instead, I chose to use html2pdf directly.
Upon directly importing html2pdf in the component where I need to add the functionality for converting html to pdf, Nuxt throws the following error: ReferenceError: self is not defined. This essentially happens because the line where the library is being imported runs on the server side as well and when it is imported, it tries to access a variable that isn't defined on the server side.
My solution was to create a custom plugin that runs only on the client side. It is very simple to do this in Nuxtv3 by just ending the filename with .client.ts as opposed to just .ts. Here is what plugins/html2pdf.client.ts looks like:
import html2pdf from 'html2pdf.js'
export default defineNuxtPlugin(() => {
// had to make a plugin because directly importing html2pdf.js in the component
// where I need to use it was causing an error as the import would run on the server
// side and html2pdf.js is a client-side-only library. This plugin runs on the
// client side only (due to the .client extension) so it works fine.
return {
provide: {
html2pdf: (element, options) => {
return html2pdf(element, options)
}
}
}
})
Now, I can safely use it in my component as:
const { $html2pdf } = useNuxtApp()
function downloadPDF() {
if (document) {
const element = document.getElementById('html2pdf')
// clone the element: https://stackoverflow.com/questions/60557116/html2pdf-wont-print-hidden-div-after-unhiding-it/60558415#60558415
const clonedElement = element.cloneNode(true) as HTMLElement
clonedElement.classList.remove('hidden')
clonedElement.classList.add('block')
// need to append to the document, otherwise the downloading doesn't start
document.body.appendChild(clonedElement)
// https://www.npmjs.com/package/html2pdf.js/v/0.9.0#options
$html2pdf(clonedElement, {
filename: 'filename.pdf',
image: { type: 'png' },
enableLinks: true
})
clonedElement.remove()
}
}
Basic usage of html2pdf: https://www.npmjs.com/package/html2pdf.js/v/0.9.0#usage
Configuration for html2pdf: https://www.npmjs.com/package/html2pdf.js/v/0.9.0#options
If someone looking for how to use html2pdf in nuxt 2.
install html2pdf.js using npm or yarn
create html-to-pdf.js file in nuxt plugin directory with below code
import html2pdf from 'html2pdf.js'
export default (context, inject) => {
inject('html2pdf', html2pdf)
}
Then add plugin to nuxt.config.js
plugins: [
'#/plugins/axios',
......
{ src: '#/plugins/html-to-pdf', mode: 'client' },
],
How to use , example in your component menthod
methods: {
export() {
this.$html2pdf(this.$refs.document, {
margin: 1,
filename: 'file-name.pdf',
image: { type: 'jpeg', quality: 0.98 },
html2canvas: {
scale: 1,
dpi: 192,
letterRendering: true,
ignoreElements: true,
},
jsPDF: { unit: 'pt', format: 'a2', orientation: 'portrait' },
})
},

electron js - cannot get button to perform simple actions from click

Long story short I am working on a single page application that sends commands over a local network. Testing out Electron JS and I can't even seem to get a simple button to work. I feel like I am not linking the logic between main.js and index.js somehow but for the life of me I cannot figure out the correct way to do it. I have even put breakpoints in index.js and through main.js & index.html but none of the breakpoints are hit aside from the ones in main.js. I put a simple function in a preload.js file and that function is correctly called but the one I am trying to attach to a button located in index.html and index.js is never even being hit. A lot of the commented out code is things I want to remember or things I have noticed a different method of creating and just wanted to try and see if that worked. If anyone has any answers or guidance it would be greatly appreciated! :D
Below is my main.js
//#region ---for dev only | hot reload
try {
require('electron-reloader')(module)
} catch (_) {}
//#endregion
const electron = require('electron');
const {app, BrowserWindow, Menu} = require('electron');
const path = require('path');
const ipcMain = electron.ipcMain;
//#region globals
const SRC_DIR = '/src/'
const IMG_DIR = '/assets/images'
//#endregion
function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600,
//frame: false,
webPreferences: {
contextIsolation: true,
preload: path.join(__dirname, 'preload.js')
}
});
//Used to auto open dev tools for debugging
//win.openDevTools();
win.loadFile('src/index.html');
// win.loadURL(url.format({
// pathname: path.join(__dirname, 'index.html'),
// protocol: 'file',
// slashes: true
// }));
}
app.whenReady().then(() => {
//nativeTheme.shouldUseDarkColors = true;
createWindow();
})
//closes app processes when window is closed
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit();
})
var menu = Menu.buildFromTemplate([
{
label: 'Menu',
submenu: [
{label: 'Edit'},
{type: 'separator'},
{
label: 'Exit',
click() {
app.quit();
}
}
]
}
])
Menu.setApplicationMenu(menu);
Here is index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
<meta http-equiv="X-Content-Security-Policy" content="default-src 'self'; script-src 'self'">
<title>Ecas Software</title>
<link rel="stylesheet" href="index.css">
</head>
<body>
<p id="myText">Let's get started :)</p>
<button id="myBtn">Change Text</button>
<script type="text/javascript" src="./index.js" ></script>
</body>
</html>
Lastly here is my index.js (aka my first and only renderer?)
const electron = require('electron');
const chgBtn = document.getElementById('myBtn');
function replaceText(selector, text){
const element = document.getElementById(selector);
if (element) element.innerText = text;
}
chgBtn.onclick = function() {
replaceText('myText', 'no boom...');
}
// chgBtn.addEventListener('click', function(){
// // if (document.getElementById('myText').innerText == 'boom'){
// // replaceText('myText','no boom...');
// // } else {
// // replaceText('myText','boom');
// // }
// document.alert("working function");
// });
//chgBtn.addEventListener('click', replaceText('myText','no boom...'));
Why you have this error
The problem here is that you didn't use your scripts files the way Electron was intended.
If you use the Devtools Console (by uncommenting win.openDevTools()), you should see this error in your console :
Uncaught ReferenceError: require is not defined (from index.js file)
This is because your index.js file is loaded as a "normal javascript file". If you want to use the Node syntaxe (aka the "require" syntaxe), you need to do it in your preload script. Only the preload script can use the require syntaxe, since it is the only script allowed by Electron to use Node.
You can also use other javascripts files, by import it in your HTML as you did for the index.js file, but you should remove the require call. As the "require" call (on the first line) will throw and error, all the following code will not run. This is why your button did not react on click.
The correct way to do it
If you need to use some methods from the Electron Renderer API (such as the ipcRenderer), you need to put it in your preload script.
If you want to use your own script, in a separate file, you can also do it, you will not be able to directly call Electron API. There is a solution if you want to call the Electron API in your own script, it is called the Context Bridge. This allows you to create an object in your preload script, that can use the Electron API. You can give this object a name, and then call it from your others script by using the window global object.
For example, if you want to use ipcRenderer.send(channel, payload) :
// Preload script
const { contextBridge, ipcRenderer } = require('electron')
contextBridge.exposeInMainWorld('theNameYouWant',
{
send: (channel, payload) => ipcRenderer.send(channel, payload)
}
)
// index.js file, imported in your HTML file
window.theNameYouWant.send("channel-name", { someData: "Hello" })
In your example
// Add this in your main.js file to see when a user click on the button from main process
ipcMain.on("button-clicked", (event, data) => console.log(data))
// Preload script
const { contextBridge, ipcRenderer } = require("electron")
contextBridge.exposeInMainWorld("electron", {
send: (channel, payload) => ipcRenderer.send(channel, payload),
})
// index.js
const chgBtn = document.getElementById("myBtn")
function replaceText(selector, text) {
const element = document.getElementById(selector)
if (element) element.innerText = text
}
chgBtn.onclick = function () {
replaceText("myText", "no boom...")
window.electron.send("button-clicked", { someData: "Hello" })
}

Electron: cannot read property 'getCurrentWebContents' of undefined

I'm trying to read the files from a directory using the fs module, and display that in a div with the id displayfiles in an Electron app. I keep getting the error :
Cannot read property 'getCurrentWebContents' of undefined
I've tried a coupld of different things to get access to the webcontents of the main window in my menu.js but I keep getting undefined errors.
My code in menu.js looks like this:
Cannot read property 'getCurrentWebContents' of undefined
const electron = require('electron');
const dialog = electron.dialog;
const fs = require('fs');
const remote = require ("electron").remote;
const template=[
{
label: 'File',
submenu: [
{
label:'Open USB',
click () { dialog.showOpenDialog( {
properties: ['openDirectory']
},directorySelectorCallback)
}
},
{
label:'Exit',
click() {
}
},
]
},
{
label: 'Edit',
submenu: [
{role: 'undo'},
{role: 'redo'},
{type: 'separator'},
{role: 'cut'},
{role: 'copy'},
{role: 'paste'},
{role: 'pasteandmatchstyle'},
{role: 'delete'},
{role: 'selectall'}
]
},
{
label: 'View',
submenu: [
{role: 'reload'},
{role: 'forcereload'},
{role: 'toggledevtools'},
{type: 'separator'},
{role: 'resetzoom'},
{role: 'zoomin'},
{role: 'zoomout'},
{type: 'separator'},
{role: 'togglefullscreen'}
]
},
{
role: 'window',
submenu: [
{role: 'minimize'},
{role: 'close'}
]
},
]
function directorySelectorCallback(filenames) {
console.log("test:");
if (filenames && filenames.length > 0) {
console.log(filenames[0]);
fs.readdir(filenames[0], (err, files) => {
'use strict';
if (err) throw err;
//the files parameter is an array of the files and folders in the path we passed. So we loop through the array, printing each file and folder
for (let file of files) {
//the += after innerHTML means we are appending to the existing content
remote.getCurrentWebContents().executeJavaScript(`
document.getElementById("display-files").innerHTML += '<li> ${file} </li>'
`)
}
});
}
}
module.exports.template=template;
Here is my index.html file:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Rexnord</title>
</head>
<body>
<div ><ol id="display-files"></ol></div>
<script>
// You can also require other files to run in this process
require('./renderer.js')
require('./menu/menu.js')
</script>
</body>
</html>
Here is my main.js file:
// Modules to control application life and create native browser window
const electron = require('electron')
const {app, BrowserWindow,Menu} = require('electron')
const menuTemplate=require('./menu/menu.js')
// 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.
var mainWindow
function createWindow () {
// Create the browser window.
mainWindow = new BrowserWindow({width: 800, height: 600,icon: __dirname + '/Rexnord.ico'})
// and load the index.html of the app.
mainWindow.loadFile('index.html')
// Open the DevTools.
mainWindow.webContents.openDevTools()
// Emitted when the window is closed.
mainWindow.on('closed', function () {
// 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.
mainWindow = null
})
let menu = Menu.buildFromTemplate(menuTemplate.template)
Menu.setApplicationMenu(menu);
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)
// Quit when all windows are closed.
app.on('window-all-closed', function () {
// 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', function () {
// 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 (mainWindow === null) {
createWindow()
}
})
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
module.exports.mainWindow=mainWindow;
How would I get access to the web contents of the main window in my menu.js file so I can manipulate the html?

Angular2 / Electron application using electron API within the angular2 ts files

I have setup an angular2 / Electron app similar to the explanation in this video : https://www.youtube.com/watch?v=pLPCuFFeKOU. The project I am basing my code on can be found here : https://github.com/rajayogan/angular2-desktop
I am getting the error:
app.ts:16Uncaught TypeError: Cannot read property 'on' of undefined
When I try to run this code:
import { bootstrap } from '#angular/platform-browser-dynamic';
import { Component } from '#angular/core';
import { MenuComponent} from './menu';
import { ConfigEditorComponent } from './config-editor';
import { remote, ipcRenderer} from 'electron';
let {dialog} = remote;
//Functions used for select server xml callbacks.
const ipc = require('electron').ipcMain
const xml2js = require('xml2js')
const fs = require('fs')
var parser = new xml2js.Parser();
ipc.on('open-file-dialog', function (event) {
dialog.showOpenDialog({
title:"Select zOS Connect server.xml",
properties: ['openFile', 'openDirectory'],
filters: [
{name: 'XML', extensions: ['xml']},
{name: 'All Files', extensions: ['*']}
]
}, function (files) {
if (files){
fs.readFile(files[0], function(err, data) {
parser.parseString(data, function (err, result) {
console.dir(result);
process_server_xml(event,result);
})
})
}
})
})
function process_server_xml(event,json){
console.log("oh hello!")
event.sender.send('selected-directory', json)
console.log("oh im done!")
}
#Component({
selector: 'connect-toolkit',
templateUrl: 'app.component.html',
directives: [ MenuComponent, ConfigEditorComponent ]
})
export class AppComponent {
constructor() {
var menu = remote.Menu.buildFromTemplate([{
label: 'Raja',
submenu: [
{
label: 'open',
click: function(){
dialog.showOpenDialog((cb) => {
})
}
},
{
label: 'opencustom',
click: function(){
ipcRenderer.send('open-custom');
let notification = new Notification('Customdialog', {
body: 'This is a custom window created by us'
})
}
}
]
}])
remote.Menu.setApplicationMenu(menu);
}
}
bootstrap(AppComponent);
I think the problem may be:
const ipc = require('electron').ipcMain
const xml2js = require('xml2js')
const fs = require('fs')
var parser = new xml2js.Parser();
Is it possible require doesn't work here, and somehow I need to use import statements instead from my ts files? If this is the case how do I use the import in order to get the ipcMain object and my xml2js etc?
Why would that be the case? How can I make require work within the ts files if this is the problem.
Note that if I remove the require lines, and all the ipc.on code everything runs as expected and works fine (other than the fact that the ipc event is never received ;)
Calling ipcMain doesn't work because you're not on main (i.e., the electron side code, which is on electron index.js file), your are on renderer (web page). Therefore you must use ipcRenderer instead, which is already imported using es6 import syntax on top of your app.ts file. And if you want to make something using electron ipcMain, it have to be done from the electron code side.
import {remote, ipcRenderer} from 'electron';
Electron ipc notes:
ipcMain Communicate asynchronously from the main process to renderer processes.
ipcRenderer Communicate asynchronously from a renderer process to the main process.

Categories

Resources