Pre-load a JS file in puppeteer - node.js

I have a javascript file which spoofs browser properties. how can I preload I before loading any website?
I used to work with nightmare JS. we are using this
command
node main.js data-spoof.js "$proxy"
inside main.js file
var args = process.argv.slice(2);
var proxystr = 'socks4://' + args[1].replace(/"/g, '');
webPreferences: {
preload: path.resolve(args[0]),
},
switches: {
'proxy-server': proxystr,
},
}
}

Can page.evaluateOnNewDocument(pageFunction[, ...args]) help?

Related

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.

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!

Electron - "Cannot read property 'on' of undefined"; tried reinstalling,

I'm testing an electron app but I'm getting this pernicious error:
"TypeError: Cannot read property 'on' of undefined"
The research I've done pointed to either a botched module install, a syntax issue, or passing in an undefined variable to the app.on, and I suspect the issue may be Electron being pointed to incorrectly (now it's being pointed to the folder ending in electron\dist\electron.exe, which I've heard might not the right location), but I'm unsure.
Despite checking the require command, syntax, rechecking, uninstalling, and reinstalling node, I can't seem to make this darn error go away. What could be causing this?
const electron = require('electron');
const os = require('os');
const fs = require('fs');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
var Mousetrap = require('mousetrap');
const path = require('path');
const url = require('url');
const ipc = electron.ipcMain;
let mainWindow;
function createWindow () {
// Create the browser window.
mainWindow = new BrowserWindow({width: 800, height: 600})
// and load the index.html of the app.
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
/* More code in this and sub functions*/
}))
}
})
const preferencesManager = require('./preferencesManager');
/******
Send data to database given constructor created in preferencesManager
******/
// First instantiate the class because we want to turn the class into an object to be able to use.
const store = new Store({ //create a new getting and setting logic
//We'll call our data file 'user-preferences'
configName: 'user-preferences',
defaults: {
//800 x 600 is the default size of our window
windowBounds: { width: 800, height: 600}
}
});
// When our app is ready, we'll create our BrowserWindow
app.on('ready',function(){
//Set up a listener for what I've done in keycapture (in the renderer process)
//???
ipc.on('invokeAction', function(event, args){
/* Do some action */
});
});
You are probably trying to run your application like a node app with:
$ node index.js
The electron file is a binary file, not a JavaScript file, when you require it an run with node there will be no object to call electron.app, so it parses for null and cannot have an property. As in the getting started documento of Electron.JS you must run the application like this:
Change your package.json script session adding start:
{
"scripts": {
"start": "electron ."
}
}
Now run:
$ npm start
The code you posted has an error, witch may be an edition error while coping and pasting but it should loose some parenthesis and curly brackets:
function createWindow () {
// Create the browser window.
mainWindow = new BrowserWindow({width: 800, height: 600})
// and load the index.html of the app.
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
/* More code in this and sub functions*/
}))
}
The application should now run correctly. I tested you exact code, removing the libs I did not have and it loaded with no errors.

Electron - How to load a html file into the current window?

I was looking all around: docs, google, etc., on how to load a html file in the main window of an electron app, but I can't find a way.
Is it really this complicated or dead simple?
With what I have came up is ajax, thus works:
$("#main").load("./views/details.html");
Another method I have found is via remote:
const {BrowserWindow} = require('electron').remote
let win = new BrowserWindow({width: 800, height: 600})
win.loadURL('https://github.com')
But this opens always a new window, and I need to replace the existing page
If you want to load a new URL in an existing window you can do this in the renderer process:
const { remote } = require('electron')
remote.getCurrentWindow().loadURL('https://github.com')
Note that Electron restarts the renderer process when a new URL is loaded, so you'll probably see a flash when that happens. This is why it's usually best to use a single page application (SPA) architecture when building Electron apps.
I know this post is quite old but it's the most popular one on Google in terms of the question of loading new layouts for windows.
I had the same white flash issue because I'm not using any single page framework like React or Vue.js (I'm planning to in the future). So if you are not using too, you can create a function on the main process that hides or shows which window you want to show to make it look like one-page app.
You can get and set each windows' size and position to make the transition better:
function loadPage(page) {
if (page == "landing") {
landingWindow.setSize(uiWindow.getSize()[0],uiWindow.getSize()[1])
landingWindow.setPosition(uiWindow.getPosition()[0],uiWindow.getPosition()[1])
landingWindow.show()
uiWindow.hide()
} else if (page == "main") {
uiWindow.getSize(landingWindow.getSize()[0],landingWindow.getSize()[1])
uiWindow.setPosition(landingWindow.getPosition()[0],landingWindow.getPosition()[1])
uiWindow.show()
landingWindow.hide()
}
exports.loadPage = loadPage;
And you can expose this function to window with a preload script like this:
const electron = require('electron')
const remote = electron.remote
const mainProcess = remote.require('./main')
window.loadPage = mainProcess.loadPage;
Don't forget to initialize both windows on the main process:
function createWindow() {
// Create the browser window.
landingWindow = new BrowserWindow({
width: 1820,
height: 720,
/* fullscreen: true, */
webPreferences: {
nodeIntegration: false,
preload: path.resolve(path.join(__dirname, "preloads/preload.js"))
},
show: false,
backgroundColor: "#222831"
});
landingWindow.loadURL(
url.format({
pathname: path.join(__dirname, "src/landing.html"),
protocol: "file:",
slashes: true
})
);
uiWindow = new BrowserWindow({
width: 1820,
height: 720,
/* fullscreen: true, */
webPreferences: {
nodeIntegration: false,
preload: path.resolve(path.join(__dirname, "preloads/preload.js"))
},
show: false,
backgroundColor: "#222831"
});
uiWindow.loadURL(
url.format({
pathname: path.join(__dirname, "src/mainui.html"),
protocol: "file:",
slashes: true
})
);
// and load the index.html of the app.
// Open the DevTools.
landingWindow.webContents.openDevTools();
// Emitted when the window is closed.
landingWindow.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.
landingWindow = null;
});
landingWindow.once("ready-to-show", () => {
landingWindow.show();
});
}

Can't find css.js when using r.js

I am compiling my require.js based JavaScript together with r.js. We use the css plugin. Here is my build.js that I am running:
var requirejs = require('requirejs');
var sys = require("sys");
var prop = require("./node/config.js");
var extend = require('node.extend');
var baseNoC=prop.base.replace("C:/","");
window = {
top: {
M4_CONFIG: {
path: prop.base + "/uif/trunk"
}
}
};
var amdConfig = require(prop.base + "/uif/trunk/scripts/bootstrap/amd-config");
var config = {
baseUrl: "C:",
name: "/"+baseNoC+"/uif/trunk/scripts/bootstrap/home-main.js",
out: "main-built.js",
optimize: "none",
map: {
'*': {
'css': baseNoC + "/vendor/trunk/require-plugins/require-css/0.0.3/css"
}
}
};
config = extend(config, amdConfig);
config.paths["all-files"]= window.top.M4_CONFIG.path + "/all-files";
//I tried it with this line in and out.
//config.paths["css"]="Projects/mercury/vendor/trunk/require-plugins/require-css/0.0.3/css";
requirejs.optimize(config, function(buildResponse) {
//buildResponse is just a text output of the modules
//included. Load the built file for the contents.
//Use config.out to get the optimized file contents.
var contents = fs.readFileSync(config.out, 'utf8');
}, function(err) {
//optimization err callback
sys.puts("error! " + err);
});
When I run my page with my generated JavaScript, I get "NetworkError: 404 Not Found - [domain]/css.js"
The location of the file is in the location specified on my config.map. Anyway, I don't understand why it isn't in my compiled JavaScript. What should I do?
P.S.
We're using Sass and I wouldn't mind just packaging up one big css with Sass and telling it to ignore the !css in the code. (However, those are in there for historical reasons.)
The issue is a bug in the r.js compiler, where it is ignoring the map config. I was just bitten by the same issue. I'm working on getting it resolved.

Resources