How do run reload() and open() in Atom-Shell - javascript

1) Is this javascript call not supported on Atom-shell?
window.open('#/openpage','_self',false)
2) In NodeJS-Webkit, I could either reload the HTML with win.reload() without the toolbar and buttons. Is Atom-shell support this API as well?
3) In the app.js that is program to index.html into the Atom-shell
var BrowserWindow = require('browser-window');
and index.html tried to execute a reload command and failed that BrowserWindow is not defined.
BrowserWindow.reload()

browser-window only works in the Browser process (i.e. the one your app starts in). Try this:
var remote = require('remote');
remote.getCurrentWindow().reload();

For Reload :
const { BrowserWindow } = require('electron').remote
BrowserWindow.getCurrentWindow().reload();
For Close:
BrowserWindow.getCurrentWindow().on('close', () => {
// window was closed...
})
Documentation :
https://www.electronjs.org/docs/api/remote

Related

Problems with Testcafe LocalStorage

everyone!
I'm new to TestCafe and I need some help on something I want to achieve.
I have a React website where I put a Facebook Login. Normally, when you enter the page and click on Login with facebook a popup window opens and enter your credentials normally. After that, you are redirected to the page and the token is saved in a localStorage variable for the page to consult later on.
However, when I run test for login process, Testcafe instead of opening a popup window, opens the facebook form on the same page and never redirects to the page.
Also, I tried to set some dummy token on the localstorage using the ClientFunction (and also Roles) and my website can never reach that token because testcafe seems to put this variable on a key called hammerhead
So, my question here is, how could I enter this token on the test or manually so my website can read it and make some functions with it?
This is what I have so far.
/* global test, fixture */
import { WelcomePage } from './pages/welcome-page'
import {ClientFunction, Role} from 'testcafe';
const welcomePage = new WelcomePage()
const setLocalStorageItem = ClientFunction((prop, value) => {
localStorage.setItem(prop, value);
});
const facebookAccUser = Role(`https//mypage.net/`, async t => {
await setLocalStorageItem('token', 'my-token');
}, { preserveUrl: true });
fixture`Check certain elements`.page(`https//mypage.net/`)
test('Check element is there', async (t) => {
await t
.navigateTo(`https//mypage.net/`)
.wait(4000)
.useRole(facebookAccUser)
.expect(cetainElementIfLoggedIn)
.eql(certainValue)
.wait(10000)
})
Any help would be highly appreciated
Thanks for your time.
UPDATE FROM FEB 2021
TestCafe now supports multiple browser windows and you can log-in via the Facebook popup form without any issues. Refer to the Multiple Browser Windows topic for more information.
Currently, TestCafe does not support multiple browser windows. So it's impossible to log in via the Facebook popup form.
However, there is a workaround. Please refer to the following thread https://github.com/DevExpress/testcafe-hammerhead/issues/1428.
My working test look like this:
import { Selector, ClientFunction } from 'testcafe';
const patchAuth = ClientFunction(() => {
window['op' + 'en'] = function (url) {
var iframe = document.createElement('iframe');
iframe.style.position = 'fixed';
iframe.style.left = '200px';
iframe.style.top = '150px';
iframe.style.width = '400px';
iframe.style.height = '300px';
iframe.style['z-index'] = '99999999';
iframe.src = url;
iframe.id = 'auth-iframe';
document.body.appendChild(iframe);
};
});
fixture `fixture`
.page `https://www.soudfa.com/signup`;
test('test', async t => {
await patchAuth();
await t
.click('button.facebook')
.switchToIframe('#auth-iframe')
.typeText('#email', '****')
.typeText('#pass', '****')
.click('#u_0_0')
.wait(30e3);
});
Please keep in mind that manipulations with x-frame-options in the testcafe-hammerhead module are required.
In addition, I would like to mention that Testing in Multiple browser windows is one of our priority tasks, which is a part of TestCafe Roadmap

Argv[1] returns unexpected value when I open a file on double click in Electron app

I am trying to open a file on double click. The file is being built for the Mac App Store using electron-packager.
I have things set up so that my electron app opens when the file is double clicked, however the filename of the double clicked file is not passed to the app in the command line parameters.
The data being returned for argv[0] is the app path (as expected), and for argv[1] is something similar to -psn_0_857362. I was under the impressions argv[1] would be the path to the requested file, which is what I am looking for.
A simplified version of the code I am using (in main.js) is:
ipcMain.on(
'getOpenFile',
function( e ) {
let data = null;
if ( process.argv.length >= 2 ) {
data = process.argv[1];
}
e.returnValue = data;
}
);
Why is it not displaying the path? Is this not possible with the mac app store or do I need to do something else to make it work as expected?
On macOS, you may have to listen to the app event open-file from the main process:
app.on('open-file', (event, path) =>
{
event.preventDefault();
console.log(path);
});

Electron load remote URL and execute javascript

I'm trying to load a website in electron by loading an URL like this
mainWindow.loadURL('http://localhost/index.html')
but like this the javascript on the website doesn't load.
The following solution works:
Add the following code around the app.js that is loaded in the index.html
<script>if (typeof module === 'object') {window.module = module; module = undefined;}</script>
<script src="/app/app.js"></script>
<script>if (window.module) module = window.module;</script>
but is not optimal as I'm most likely not allowed to change the code of the website itself.
Are there any other options for simply wrapping a website in electron?
You'll want to set nodeIntegration to false in your BrowserWindow settings. That should resolve the issue. Have a look at webPreferences on this page: https://github.com/electron/electron/blob/master/docs/api/browser-window.md
This is just example add to Chris Riebschlager's answer.
Load google.com in main.js
let googleWindow;
// handle create googleWindow
function createGoogleWindow(){
googleWindow = new BrowserWindow({
webPreferences: {
nodeIntegration: true,
preload:`${__dirname}/scripts/googleWindow.js`
}});
//load html into window
googleWindow.loadURL('https://www.google.com/');
//garbage collection handle
googleWindow.on('close', function(){
googleWindow=null;
});
}
Script googleWindow.js referenced above:
const electron = require('electron');
function search(){
const input = document.querySelector('input[name="q"]');
input.value = "test";
}
setTimeout(function(){ alert("Hello");search(); }, 3000);
The above script alert "Hello" after 3 seconds, and enter "test" in the search box on google.com.
You can also send an event from the main process as a trigger, use the webContents of the window.

Open browser and reload on source code changes

Basically I want to open the default browser (which I handled already) and when the development folder has any changes (which I handled already) to use the browser reference to reload the url.
This is what I have done so far:
var open = requires('opn');
var fs = requires('fs');
var promise = open('http://localhost/my-developemnt-path/:80');
var browser;
promise.then((cp) => {
//get a reference to the browser from the child process cp
browser = cp;//...??
});
fs.watch('my-developemnt-path', {recursive: true}, (eventType, filename) => {
console.log(`event type is: ${eventType}`);
if (filename) {
console.log(`filename provided: ${filename}`);
browser && browser.location.reload();
} else {
console.log('filename not provided');
}
});
So how do I get the browser reference out of the child-process and how can I use it to force a reload?
CLARIFICATIONS
I am not using any Express or other particular application. Just a common web app I am running on Apache.
I am using nodejs just to open a browser window and monitor files changes under the working dir.

Retry loading a webpage when failed in electron

I'm using electron to display some webpages. Below is my coding:
var app = require('app');
var ipc = require('ipc');
var BrowserWindow = require('browser-window');
var settings = require('./settings');
var mainWindow = null;
app.on('window-all-closed', function() {
if (process.platform != 'darwin') {
app.quit();
}
});
app.on('ready', function(){
var mainWindow = new BrowserWindow({
fullscreen: true,
autoHideMenuBar: true
})
mainWindow.loadUrl('file://' + __dirname + '/index.html') // FIRST WEBPAGE
mainWindow.on('closed', function() {
mainWindow = null;
});
ipc.on('redirect', function(){
mainWindow.loadUrl('http://192.168.1.10/page2') // SECOND WEBPAGE
mainWindow.webContents.on("did-fail-load", function() {
console.log("did-fail-load");
mainWindow.loadUrl('file://' + __dirname + '/index.html');
// REDIRECT TO FIRST WEBPAGE AGAIN
});
});
It will first go into the first webpage, then after it received a command "redirect" from the javascript using ipc module, it will redirect to a second webpage. But I need to check whether or not the second webpage can be connected. If it cannot be connected (did-fail-load), it will go to the first webpage again. And the cycles goes on.
I use the console.log("did-fail-load") to check whether or not it had failed to connect to the second page. But I found out that it had duplicated the call. The first time it fail to connect to second webpage, there is one console.log("did-fail-load"), when it retry the second time, there is two console.log("did-fail-load") appear, and the 3rd time it retry, there is three console.log("did-fail-load") appear. Is it that it some how got duplicated calls on mainWindow?
What is the best way to retry loading a webpage when it failed in electron?
This is an old post, but I feel the question was never actually answered for OP.
You are seeing multiple console.log messages because a new did-fail-load callback is added everytime a redirect happens. You need to add the callback only once, outside of the ipc.on('redirect') callback. Example:
app.on('ready', function(){
var mainWindow = new BrowserWindow({
fullscreen: true,
autoHideMenuBar: true
})
mainWindow.loadUrl('file://' + __dirname + '/index.html') // FIRST WEBPAGE
mainWindow.on('closed', function() {
mainWindow = null;
});
/* Set did-fail-load listener once */
mainWindow.webContents.on("did-fail-load", function() {
console.log("did-fail-load");
mainWindow.loadUrl('file://' + __dirname + '/index.html');
});
});
/* This is called every time a redirect occurs,
* so don't add any listeners here. Only add code
* to handle the redirect
*/
ipc.on('redirect', function(){
mainWindow.loadUrl('http://192.168.1.10/page2') // SECOND WEBPAGE
});
You have to ask yourself the question: "Why did the load fail?" and "Would it load now?"
The why defines the best way how to check if your webpage would load. When you check the url/server before you load you make sure that it can be loaded. Then it won't be a need to reload.
From your code I would guess, that you want to check if the server inside your network is running.
To do that you could use the node module node-net-ping https://github.com/stephenwvickers/node-net-ping
Install the module via npm inside your app:
npm install node-net-ping --save
Load the module on top via require:
var ping = require ("net-ping");
Check if their server is available:
var session = ping.createSession ();
session.pingHost ('192.168.1.10', function (error, target) {
if (!error)
// Load second page
});
Another maybe better solution is to check the request before you load the url. This is also done with the node.js part of electron. Answer is copied from here:
Node.js - How to check status of a URL within a http request
var request = require('request');
request('http://www.google.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log("URL is OK")
// Load second page
}
Depending on the answer to "Why did the load fail?" you should create the check.

Categories