How to show console.log messages in Electron's BrowserWindow? - electron

Is there a way to send console.log messages to Electron's BrowserWindow ?
There is another way around described here: Electron: Send message from BrowserWindow to Electron app
The need behind such an integration is that many applications like systeminformation using console.log calls to display information
Typical call is:
const si = require('systeminformation');
si.cpu()
.then(data => console.log(data))
Alternative might be different call to send data to browser window instead of console.

By enabling Dev tool, you can see the console.log message.
win.webContents.openDevTools(); //for debugging
// To send message to web page
win.webContents.send("message", message-content);

Here is what work for me:
In main.js:
const {ipcMain} = require('electron')
and replace
console.log(data);
with
mainWindow.webContents.send('asynchronous-message', data);
Changes in render.js:
ipcRenderer.on('asynchronous-message', (event, data) => {
document.getElementById('log').insertAdjacentHTML('beforeend',data + "<br>");
})
In html - create div with id='log'

Related

Can't interact with chrome extension page with playwright

I want to automate metamask chrome extension with playwright. I found the code below in the API document. I'm able to load Metemask extension but when I try to click the Get Started button on the metamask home page it shows timeout error waiting for the selector.
I need help to check what is the problem and how to work with backgroundpage
(async () => {
const pathToExtension = require('path').join(__dirname, 'my-extension');
const userDataDir = '/tmp/test-user-data-dir';
const browserContext = await chromium.launchPersistentContext(userDataDir,{
headless: false,
args: [
`--disable-extensions-except=${pathToExtension}`,
`--load-extension=${pathToExtension}`
]
});
const backgroundPage = browserContext.backgroundPages()[0];
// Test the background page as you would any other page.
await backgroundPage.click('.btn-primary') // Get Started button
await browserContext.close();
})();
Background page is invisible and doesn't have the button you are trying to click. What you need is to be able to click on elements inside the extension popup window which is currently not supported. Please thumb up this feature request https://github.com/microsoft/playwright/issues/5593 if you need it.

Electronjs ipcMain doesn't send message to ipcRenderer

I'm trying to send message/data from ipcMain to ipcRender asynchronously, followed the codes described there - https://electronjs.org/docs/api/ipc-main, In main -
// In main process.
const {ipcMain} = require('electron')
ipcMain.on('asynchronous-message', (event, arg) => {
console.log(arg) // prints "ping"
event.sender.send('asynchronous-reply', 'pong')
})
In renderer -
// In renderer process (web page).
const {ipcRenderer} = require('electron')
ipcRenderer.on('asynchronous-reply', (event, arg) => {
console.log(arg) // prints "pong"
})
ipcRenderer.send('asynchronous-message', 'ping')
It sends message from renderer to main successfully, but main suppose to send back message to renderer but it doesn't.
I've tried webContents send message too but no success -
win.webContents.send('asynchronous-reply', 'pong1')
I'm using using node 8.9.3, Chrome 61.0.3163.100, Electron 2.0.5 and macOS 10.13.3. Here are the details - https://github.com/electron/electron/issues/13743
Appreciate any help. Thanks
Thanks #ancode. Figured it out, The messages sent from Renderer to Main was printing in Terminal Console and message sent from Main to Renderer was printing in Web Dev Console(As a new electron developer, I completely missed it, was expecting all messages in Terminal Console)

Electron handle console.log messages in main process

Is there way to handle console.log messages from renderer in main process? Similar to CefDisplayHandler::OnConsoleMessage handler in Cef.
You can do this in three ways,
Set the enviroment variableELECTRON_ENABLE_LOGGING=true to parse every console.log to your CLI
Do a IPCrenderer message to IPCmain, which the logs it for you
Add a function to app from the main process
# MAIN
const {app} = require('electron')
app.MySuperCoolLoggingUtility = function (msg) {
console.log(msg)
}
# RENDERER
require('electron').remote.app.MySuperCoolLoggingUtility('hi')
There are also some ways to limit the log level for specific files via --vmodule= but it is not close to the handler of normal Cef. So you will probably build your own utility function for it.
The ability to intercept console messages generated by the renderer process, in the main process, was implemented in Electron version v1.8.2-beta.3 (as far as I were able to determine).
To be able to handle these messages, one attaches a "console-message" event handler to the webContents object property of a BrowserWindow object.
A rather straightforward replication of messages by the main process, could be implemented as follows (win refers to a BrowserWindow you want to capture messages for):
const log_level_names = { "-1": "DEBUG", "0": "INFO", "1": "WARN", "2": "ERROR" };
win.webContents.on("console-message", (ev, level, message, line, file) => {
console.log(`${new Date().toUTCString()}\t${log_level_names[level]}\t${message} (${file}:${line})`);
});

Passing Data to Windows in Electron

I'm learning Electron and working with multiple windows and IPC. In my main script I have the following:
var storeWindow = new BrowserWindow({
width: 400,
height: 400,
show: false
});
ipc.on('show-store-edit', function(event, store) {
console.log(store);
storeWindow.loadURL('file://' + __dirname + '/app/store.html');
storeWindow.show();
});
And in my primary window's script, I have the following inside of a click event handler, pulling in a list of stores:
$.getJSON("http://localhost:8080/stores/" + item.id).done(function(store) {
ipc.send('show-store-edit', store);
});
On the console, I am printing the store data from my server. What I'm unclear on is how to get that data into the view for my storeWindow:store.html. I'm not even sure I'm handling the sequence of events correctly but they would be:
click Edit Store
get store data from server
open new window to display store data
or
click Edit Store
open new window to display store data
get store data from server
In the latter, I'm not sure how I would get the ID required to fetch the store from the storeWindow's script.
To send events to particular window you can use webContents.send(EVENT_NAME, ARGS) (see docs). webContents is a property of a window instance:
// main process
storeWindow.webContents.send('store-data', store);
To listen for this event being sent, you need a listener in a window process (renderer):
// renderer process
var ipcRenderer = require('electron').ipcRenderer;
ipcRenderer.on('store-data', function (event,store) {
console.log(store);
});
You need the ipcMain module to achieve this... As stated in the API "When used in the main process, it handles asynchronous and synchronous messages sent from a renderer process (web page). Messages sent from a renderer will be emitted to this module."
API Docs for the ipcMain module:
https://electronjs.org/docs/api/ipc-main
To use the ipcMain you need to have nodeIntegration enabled on webPreferences
win = new BrowserWindow({
webPreferences: {
nodeIntegration: true,
}
})
Be careful this may cause security issues.
For example: Let's say we want to pass a configuration (json) file to the web page
(Triple dots (...) represent your code that is already placed inside the file, but is not relevant to this example)
main.js
...
const { readFileSync } = require('fs') // used to read files
const { ipcMain } = require('electron') // used to communicate asynchronously from the main process to renderer processes.
...
// function to read from a json file
function readConfig () {
const data = readFileSync('./package.json', 'utf8')
return data
}
...
// this is the event listener that will respond when we will request it in the web page
ipcMain.on('synchronous-message', (event, arg) => {
console.log(arg)
event.returnValue = readConfig()
})
...
index.html
...
<script>
<!-- import the module -->
const { ipcRenderer } = require('electron')
<!-- here we request our message and the event listener we added before, will respond and because it's JSON file we need to parse it -->
var config = JSON.parse(ipcRenderer.sendSync('synchronous-message', ''))
<!-- process our data however we want, in this example we print it on the browser console -->
console.log(config)
<!-- since we read our package.json file we can echo our electron app name -->
console.log(config.name)
</script>
To see the console of the browser you need to open the dev tools, either from the default Electron menu or from your code.
e.g. inside the createWindow() function
win.webContents.openDevTools()

PhoneGap InAppBrowser: open iOS Safari Browser

In our PhoneGap iOS application, we are using the InAppBrowser plugin to display some content, and we need to open a page in Safari from within the InAppBrowser.
How can we have links from within the InAppBrowser open in Safari?
From the phonegap documentation:
Opens a URL in a new InAppBrowser instance, the current browser instance, or the system browser.
var ref = window.open(url, target, options);
ref: Reference to the InAppBrowser window. (InAppBrowser)
url: The URL to load (String). Call encodeURI() on this if the URL contains Unicode characters.
target: The target in which to load the URL, an optional parameter that defaults to _self. (String)
_self: Opens in the Cordova WebView if the URL is in the white list, otherwise it opens in the InAppBrowser.
_blank: Opens in the InAppBrowser.
_system: Opens in the system's web browser.
So to answer your question, use:
window.open(your_url, '_system', opts);
Note that the domain will need to be white-listed.
Update 4/25/2014:
I think I kind of misunderstood the question (thanks to commenter #peteorpeter) -- you want to have some way to click a link in the InAppBrowser and have that open in the system browser (e.g. Mobile Safari on iOS). This is possible, but it will require some forethought and cooperation between the app developer and the person responsible for the links on the page.
When you create an IAB instance, you get a reference to it back:
var ref = window.open('http://foo.com', '_blank', {...});
You can register a few event listeners on that reference:
ref.addEventListener('loadStart', function(event){ ... });
This particular event is fired every time the URL of the IAB changes (e.g. a link is clicked, the server returns a 302, etc...), and you can inspect the new URL.
To break out into the system browser, you need some sort of flag defined in the URL. You could do any number of things, but for this example let's assume there's a systemBrowser flag in the url:
.....html?foo=1&systemBrowser=true
You'll look for that flag in your event handler, and when found, kick out to the system browser:
ref.addEventListener('loadStart', function(event){
if (event.url.indexOf('systemBrowser') > 0){
window.open(event.url, '_system', null);
}
});
Note that this is not the best method for detecting the flag in the url (could lead to false positives, possibly) and I'm pretty sure that PhoneGap whitelist rules will still apply.
Unfortunately target=_system does not work from within the InAppBrowser. (This would work if the link originated in the parent app, though.)
You could add an event listener to the IAB and sniff for a particular url pattern, as you mention in your comments, if that fit your use case.
iab.addEventListener('loadstart', function(event) {
if (event.url.indexOf("openinSafari") != -1) {
window.open(event.url, '_system');
}
}
The 'event' here is not a real browser event - it is a construct of the IAB plugin - and doesn't support event.preventDefault(), so the IAB will also load the url (in addition to Safari). You might try to handle that event within the IAB, with something like:
iab.addEventListener('loadstop', function(event) {
iab.executeScript('functionThatPreventsOpenInSafariLinksFromGoingAnywhere');
}
...which I have not tested.
This message is for clarification:
If you open an another with window.open by catching a link on loadstart, it will kill yor eventhandlers that assigned to first IAB.
For example,
iab = window.open('http://example.com', '_blank', 'location=no,hardwareback=yes,toolbar=no');
iab.addEventListener('loadstop', function(event) {console.log('stop: ' + event.url);});
iab.addEventListener('loaderror', function(event) { console.log('loaderror: ' + event.message); });
iab.addEventListener('loadstart', function(event) {
if (event.url.indexOf("twitter") != -1){
var ref2 = window.open(event.url, '_system', null);
}
});
When the second window.open executed, it will kill all the event listeners that you binded before. Also loadstop event will not be fired after that window.open executed.
I'm finding another way to avoid but nothing found yet..
window.open() doesn't work for me from within an InAppBrowser, whether or not I add a script reference to cordova.js to get support for window.open(...'_system'), so I came up with the following solution which tunnels the "external" URL back to the IAB host through the hashtag so it can be opened there.
Inside the InAppBrowser instance (I'm using AngularJS, but you can replace angular.element with jQuery or $ if you're using jQuery):
angular.element(document).find('a').on('click', function(e) {
var targetUrl = angular.element(this).attr('href');
if(targetUrl.indexOf('http') === 0) {
e.preventDefault();
window.open('#' + targetUrl);
}
});
Note that that's the native window.open above, not cordova.js's window.open. Also, the handler code assumes that all URLs that start with http should be externally loaded. You can change the filter as you like to allow some URLs to be loaded in the IAB and others in Safari.
Then, in the code from the parent that created the InAppBrowser:
inAppBrowser.addEventListener('loadstart', function(e) {
if(e.url.indexOf('#') > 0) {
var tunneledUrl = e.url.substring(e.url.indexOf('#') + 1);
window.open(tunneledUrl, '_system', null);
}
});
With this solution the IAB remains on the original page and doesn't trigger a back-navigation arrow to appear, and the loadstart handler is able to open the requested URL in Safari.

Resources