Electron handle console.log messages in main process - electron

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})`);
});

Related

Sending messages from main process to renderer in Electron in 2022

In my App I have two windows: mainWindow and actionWindow. On my mainWindow I use the ipcRenderer.on listener to receive as message from the main process when the actionWindow is closed. The message however doesn't come through.
The mainWindow is used to control actions that take place on the actionWindow (e.g. navigate to an URL, remotely close the window, ...). I want to give the user the power to move and close the actionWindow manually as well, which is why its title bar is visible and usable.
I expose ipcRenderer.invoke for two-way communication and ipcRenderer.on to the mainWindow's renderer via contextBridge in a preload file.
This is what the code looks like (based on vite-electron-builder template)
main process
const mainWindow = new BrowserWindow({
show: false, // Use 'ready-to-show' event to show window
webPreferences: {
nativeWindowOpen: true,
webviewTag: false,
preload: join(__dirname, "../../preload/dist/index.cjs"),
},
});
const actionWindow = new BrowserWindow({
// some props
})
actionWindow.on("close", () => {
console.log("window closed")
mainWindow.webContents.send("closed", { message: "window closed" });
});
preload
contextBridge.exposeInMainWorld("ipcRenderer", {
invoke: ipcRenderer.invoke,
on: ipcRenderer.on,
});
renderer (mainWindow)
window.ipcRenderer.on("closed", () => {
console.log("message received")
// do something
});
I know for a fact that
mainWindow has access to the exposed listeners, since invoke works and the actions it fires on the main process are executed on the actionWindow as supposed + the response also comes back to the renderer.
the close listener on the actionWindow works since I can see the log window closed in my console
message received doesn't appear in my dev tools console
To me this means that either
mainWindow.webContents.send doesn't work -> the message is never sent
window.ipcRenderer.on doesn't work -> the message never reaches its destination
So either my code is buggy or Electron has recently put some restrictions on one of these methods which I'm not aware of.
Any ideas?
If there is a smarter way to do this than IPC I'm also open to that.
Ok after hours of searching, trying and suffering I (almost accidentaly) found a solution to my problem. It really seems to be the case that electron simply doesn't do anything anymore when you call the on method from your renderer.
Studying the docs about contextBridge again I saw that the way I exposed invoke and on to the renderer, was considered bad code. The safer way to do this is expose a function for EVERY ipc channel you want to use. In my case using TypeScript it looks like this:
preload
contextBridge.exposeInMainWorld("ipcRenderer", {
invokeOpen: async (optionsString: string) => {
await ipcRenderer.invoke("open", optionsString);
},
onClose: (callback: () => void) => {
ipcRenderer.on("closed", callback);
},
removeOnClose: (callback: () => void) => {
ipcRenderer.removeListener("closed", callback);
},
});
renderer(mainWindow)
window.ipcRenderer.onClose(() => {
// do sth
});
window.ipcRenderer.invokeOpen(JSON.stringify(someData)).then(() => {
// do sth when response came back
});
NOTE: To prevent memory leaks by creating listeners on every render of the mainWindow you also have to use a cleanup function which is provided with removeOnClose (see preload). How to use this function differs depending on the frontend framework. Using React it looks like this:
const doSth= () => {
console.log("doing something")
...
};
useEffect(() => {
window.ipcRenderer.onClose(doSth);
return () => {
window.ipcRenderer.removeOnClose(doSth);
};
}, []);
Not only is this a safer solution, it actually suddenly works :O
Using the cleanup function we also take care of leaks.

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

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'

Track event to Google TagManager inside a ServiceWorker

I'm working on a service-worker (really a firebase cloud-messaging serviceworker like this) and I would like to track each time a user receives a push on Google TagManager.
Any help on how to include the script and send tracks within a SW?
Thanks.
The Service worker runs outside the main thread and does not have
access to the Window object, meaning that it cannot access the data
layer or the ga command queue to create trackers. In short, the
actions of a service worker cannot be tracked using the normal
on-page, JavaScript-based tracking snippets. What we can do, however,
is configure our service worker to send HTTP hits directly to GA.
Here is a sample code
fetch('https://www.google-analytics.com/collect', {
method: 'post',
body: JSON.stringify({
v: 1, // Version Number
t: eventName, // Hit Type
ec: eventCategory, // Event Category
ea: eventAction, // Event Action
el: 'serviceworker' // Event Label
})
})
If you want to get into more details, I would recommend reading this article. https://builtvisible.com/google-analytics-for-pwas-tracking-offline-behaviour-and-more/

Manually replaying requests queued by workbox-background-sync

I am working on offline support in my PWA app. I am using workbox for that. This is my current code:
const addToFormPlugin = new workbox.backgroundSync.Plugin('addToForm');
workbox.routing.registerRoute(
RegExp('MY_PATH'),
workbox.strategies.networkOnly({
plugins: [addToFormPlugin]
}),
'POST'
);
The code seems to works fine on my computer. However, once I run the app on the phone it takes ages to upload requests stored in IndexedDB. I know that it happens on the SYNC but it seems to take at least 5 minutes. This is not exactly what I need. I wonder if there is an option to access the IndexDB and send all the requests "manually" on click. Another way would be to check if the device is online. Here is how requests are stored:
If you need to force this, the cleanest approach would be to use the workbox.backgroundSync.Queue class (instead of workbox.backgroundSync.Plugin) directly.
The Plugin class takes care of setting up a fetchDidFail callback for you, so if you use the Queue class, you need to do that yourself:
const queue = new workbox.backgroundSync.Queue('addToForm');
workbox.routing.registerRoute(
RegExp('MY_PATH'),
workbox.strategies.networkOnly({
plugins: [{
fetchDidFail: async ({request}) => {
await queue.addRequest(request);
},
}],
}),
'POST'
);
You could then call queue.replayRequests() to trigger the replay, e.g., as a result of a message event:
self.addEventListener('message', (event) => {
if (event.data === 'replayRequests') {
queue.replayRequests();
}
});
But... that all being said, I think your best bet is just to let the browser "do its thing" and figure out when the right time is to replay the queued requests. That will end up being more battery-friendly for mobile devices.
If you're unhappy with the interval that the browser waits before firing a sync event, then the best course of action could be to open a bug against the browser—whether it's Chrome (as appears in your screenshot) or another browser.

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()

Resources