Run nightmare js script inside electron app - javascript

So I have this nightmarejs code I would like to execute(open new window and run the script) when you click a button inside an electron app. However I searched through the internet and nothing worked for me :/ (I have a mac)
var Nightmare = require('nightmare');
var nightmare = Nightmare({
electronPath: require('${__dirname}/node_modules/electron'),
show: true
});
nightmare
.goto('http://yahoo.com')
.type('form[action*="/search"] [name=p]', 'github nightmare')
.click('form[action*="/search"] [type=submit]')
.wait('#main')
.evaluate(function () {
return document.querySelector('#main .searchCenterMiddle li a').href
})
.end()
.then(function (result) {
document.getElementById("results").innerHTML = result;
})
.catch(function (error) {
console.error('Search failed:', error);
});
const electron = require('electron')
const app = electron.app
const BrowserWindow = electron.BrowserWindow
let mainWindow;
function createWindow() {
mainWindow = new BrowserWindow({
title: "Dummy",
fullscreenable: false,
resizable: false,
alwaysOnTop: false,
width: 420,
height: 250,
'web-preferences': {
'web-security': false
}
})
mainWindow.loadURL(`file://${__dirname}/index.html`)
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()
}
})
Thanks,
Bertram

I don't see anything that will fire off the code you want to run.
If you gave it to me to make work, I'd do two things:
wrap the nightmare code in a function so you can
require("./mynighmare.js").sleepPoorly()
in your index.html, add a button that calls the above line to actually run your code.
... then I'd do a whole bunch of testing, because my first draft wouldn't work right :)

Related

Electron send data to react with preload.js

I am trying achieve something where I can directly send data to react and where in react whenever it receives it does something.
So my electron.js is in below format.
// ./public/electron.js
const path = require("path");
const { app, BrowserWindow, ipcMain} = require("electron");
const isDev = false; //require("electron-is-dev"); //false
let splash = null;
let win = null;
let etmf_obj = null;
function createWindow() {
// Create the browser window.
win = new BrowserWindow({
width: 1920,
height: 1080,
webPreferences: {
nodeIntegration: true,
contextIsolation: true,
enableRemoteModule: true,
preload: path.join(__dirname, "./preloadDist.js"),
},
});
// win.loadFile("index.html");
win.loadURL(
isDev
? "http://localhost:3000"
: `file://${path.join(__dirname, "../build/index.html")}`
);
// Open the DevTools.
if (!isDev) {
win.webContents.openDevTools({ mode: "undocked" });
}
}
app.whenReady().then(createWindow);
app.on("window-all-closed", () => {
if (process.platform !== "darwin") {
app.quit();
}
});
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
function restartApp() {
console.log("restarting app..");
app.exit();
app.relaunch();
}
//IPC SECTION
ipcMain.handle("notify", (event, args) => {
console.log("from react I got" + args);
console.log("hello from electron via react"); //this one works as expected
});
ipcMain.on("splashDone", function () {
console.log("splash done");
});
ipcMain.on("relaunchApp", function () {
restartApp();
});
ipcMain.on("closeAll", function () {
app.quit();
});
ipcMain.on("callAnim", function (args) {
win.webContents.send("showAnimation", args);// trying to send data directly to
//react here but don't know whether its right way or not
});
and my preload file preloadDist.js is in below format
const { ipcRenderer, contextBridge } = require("electron");
contextBridge.exposeInMainWorld("electron", {
notificationApi: {
sendNotification(message) {
ipcRenderer.invoke("notify", message);
},
},
batteryApi: {},
filesApi: {},
splashStatus: {
splashDone() {
ipcRenderer.invoke("splashDone")
}
},
});
and react to call function of or to send data I am do this
for example to send notification data :
<button
className="speak_border"
onMouseEnter={() => setHovermic(true)}
onMouseLeave={() => setHovermic(false)}
onClick={() => {
soundwave();
window.electron.notificationApi.sendNotification(
"From react Hi!");
}}
>
and to receive data I am not able to figure out but as I am doing win.webContents.send("showListenAnimation", args);
I am not able to understand how this will be received at the react end
what I tried is:
useEffect(() => {
try {
window.electron.on(
"showAnimation",
function (event, data) {
if (data) {
setAnim(true);
}
if (!data) {
setAnim(false);
}
}
);
} catch (e) {
console.log("issue with on getting data");
}
});
But this way I am getting error and not able to figure out the way to receive, but sending data from react to electron is working perfectly fine!
Please guide on this and how to achieve with about preload.js and electron.js
format.

Electron - How to pass data to renderer from a new opened window?

I'm struggling to pass a data from newly opened site window to renderer. What I want to achieve is to find a login button on site and listen on click event. I was reading about webview in electron, but I couldn't make It work. For now I'm stuck on window.open() method. Can you please point me what aspect I am missing? Here are my files:
//main.js
const {app, BrowserWindow, ipcMain} = require('electron')
const path = require('path')
function createWindow () {
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
nodeIntegration: true,
contextIsolation: false,
enableRemoteModule: true
}
})
mainWindow.loadFile('index.html')
// Open the DevTools.
mainWindow.webContents.openDevTools()
}
app.whenReady().then(() => {
createWindow()
app.on('activate', function () {
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit()
})
ipcMain.on("open-login-window", () => {
console.info('dostal');
});
//renderer.js
const electron = require("electron");
const ipc = electron.ipcRenderer
const button = document.getElementById("login-button");
button.addEventListener("click", () => {
ipc.send("open-login-window")
const windowProxy = window.open('https://www.somesite.com/login', null, 'minimizable=false')
windowProxy.postMessage('hi', '*')
});

How to move ipcMain.on calls outside the main.js file

I am working on a project with Electron and React. I am going to be making multiple calls to the database via ipcMain and ipcRenderer so I moved the calls for ipcMain to another file(ipcMainHandler.js).
The challenge I am facing now is how to send responses back to the ipcRenderer. I am unable to access the mainWindow from within that file.
This is the code for my main file.
const url = require('url');
const { app, BrowserWindow } = require('electron');
let mainWindow;
function createWindow() {
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true,
preload: __dirname + '/preload.js'
},
});
const startUrl =
process.env.ELECTRON_START_URL ||
url.format({
pathname: path.join(__dirname, './build/index.html'),
protocol: 'file:',
slashes: true,
});
mainWindow.loadURL(startUrl);
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();
}
});
require('./src/server/helpers/ipcMainHandler.js');
The ipcMainHandler.js file
const { SIGNIN_REQUEST, SIGNIN_RESPONSE } = require('../../common/events.js');
const { ipcMain } = require('electron');
ipcMain.on(SIGNIN_REQUEST, (event, data) => {
const user = AuthController.userSignin({ ...data });
});
Things I have tried
Accessing the currentWindow from remote - throws a remote undefined error
Adding the mainWindow to a global variable and trying to access it in the ipcHander. - This also returns an undefined message.
This has been resolved. I used the event object to send the response from ipcMain.
ipcMain.on(SIGNIN_REQUEST, async (event, data) => {
const user = await AuthController.userSignin({ ...data });
event.sender.send(SIGNIN_RESPONSE, user);
});

How to catch event win.setContentProtection() function triggered ElectronJS

In this example I am using win.setContentProtection(true)
const { app, BrowserWindow } = require('electron')
function createWindow() {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
})
win.setContentProtection(true)
}
app.whenReady().then(createWindow)
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
console.log('I am active')
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
when screen capture application start window disappear and when it close window appear again.
But I want to catch event when application detect screen capture and hide application.
Here is the doc link: https://www.electronjs.org/docs/api/browser-window#winsetcontentprotectionenable-macos-windows
if it is not possible I want an alternative JavaScript solution like using
https://github.com/waitingsong/node-win32-api
Windows API doc link
https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setwindowdisplayaffinity
Anyone here who can help me?

Electron app opening all pages upon startup

I am setting up a multi-paged electron application, however whenever I start my application it opens all the pages, and anytime I click a button that is supposed to bring the user to the next page, it skips ahead and opens the other pages as well.
I believed the issue was with setting the parent/child relation of each window, however when commenting or removing those properties the issue persists.
const{app, BrowserWindow, ipcMain} = require('electron');
import{fstat} from 'fs';
import{resolve} from 'path';
const packagejson = require('../package.json')
app.commandLine.appendSwitch('touch-events', 'enabled');
if (require('electron-squirrel-startup')) {
app.quit();
}
let mainWindow;
let startWindow;
let setOriginsWindow;
const createWindow = () => {
startWindow = new BrowserWindow({
width: 800,
height: 600,
});
startWindow.loadURL(`file://${__dirname}/index.html`);
startWindow.webContents.openDevTools();
startWindow.on('closed', () => {
startWindow = null;
});
};
app.on('ready', createWindow);
ipcMain.on('set-origins', (event) => {
setOriginsWindow = new BrowserWindow({
})
setOriginsWindow.on('close', function() {setOriginsWindow = null});
setOriginsWindow.loadURL(`file://${__dirname}/set_origin_page.html`)
setOriginsWindow.once('ready-to-show', () => {
setOriginsWindow.show();
});
setOriginsWindow.openDevTools();
if(packagejson.ENV == "dev"){
setOriginsWindow.openDevTools();
}
})
// parent:startWindow,
// fullscreen: true,
// modal:true,
// show:false
ipcMain.on('start-procedure', (event) => {
mainWindow = new BrowserWindow({
})
mainWindow.on('close', function () {mainWindow = null});
mainWindow.loadURL(`file://${__dirname}/main_page.html`);
mainWindow.once('ready-to-show', () => {
mainWindow.show();
});
mainWindow.openDevTools();
if(packagejson.ENV == "dev"){
mainWindow.openDevTools();
}
})
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (startWindow === null) {
createWindow();
}
});
'''
The 1st page to open should be a splashscreen with button that when pressed, will open page 2. Page 2 has a button that when pressed will open page 3.
Electron is not good for multipage apps, and displays a blank screen for around a quarter of a second when changing pages. Instead, you might want to create a file with all pages combined and switch between them with DOM methods
For Example
var splash_screen = document.getElementById('splash-screen');
var second_screen = document.getElementById('second-screen');
var third_screen = document.getElementById('third-screen');
document.removeChild(second_screen)
document.removeChild(third_screen)
var splash_button_click = () => {
document.removeChild(splash_screen);
document.appendChild(second_screen);
}

Categories

Resources