Electron: remove beforeunload event listeners - electron

I have an electron-application that is used to show webpages which I have no control over.
The app is used so a different page can be shown every few seconds.
One of the pages shown attaches an 'beforeunload' listener like so
window.addEventListener('beforeunload', function(event) {
event.returnValue="test";
});
This causes electron to fail when loading a new url, so the switching does not work anymore.
This is a known issue: https://github.com/electron/electron/issues/9966
Even worse, is also prevents the whole application from being closed.
Is there anything that can be done from the main process that removes/disables the beforeunload listener, so the switching works again?
To test this, I have a fiddle that shows this behavior:
https://gist.github.com/9a8acc3bf5dface09d46aae36807f6f9

You can simply prevent this event:
const { BrowserWindow, dialog } = require('electron')
const win = new BrowserWindow({ width: 800, height: 600 })
win.webContents.on('will-prevent-unload', (event) => {
event.preventDefault()
})
See Electron docs for details

Related

Electron: Maximize Window on Start

I'm creating a electron app and am trying to allow it to open so that it is maximized on start. Is there a function of some kind that you put in the main.js to maximize the window? Thanks!
win.maximize() will maximize your window.
One caveat: even if you instantly call this function after creating the BrowserWindow you may still see the small window before maximizing. So hiding the window and showing it only after maximizing should do the trick.
const { BrowserWindow, app } = require("electron");
let win;
app
.whenReady()
.then(() => {
win = new BrowserWindow({
show: false,
});
win.maximize();
win.show();
})
.catch(console.error);

How to set mouse click as global shortcut in electron app

I want to trigger an action on double right-click of mouse when electron app is running in the background.
I read the documentation and seems like there are no globalshortcuts for mouse events.
Any other way to achieve this? perhaps some node module compatible with electron app?
Unfortunately, we can't achieve that yet.
As MarshallOfSound commented on this official issue
"globalShortcut intercepts the key combination globally and prevents any application from receiving those key events. If you blocked apps from receiving mouse button presses things would break everywhere very quickly 👍"
https://github.com/electron/electron/issues/13964
For macOS, I'm currently using Keyboard Maestro App.
I'm getting my mouse keys with this app and triggering a globalShortcut key combination register in my Electron App.
Maybe for Windows, AHK (auto hot keys)
I found this nice solution for HTML code
<script type = "text/javascript">
const {remote} = require('electron')
const {Menu, MenuItem} = remote
const menu = new Menu()
// Build menu one item at a time, unlike
menu.append(new MenuItem ({
label: 'MenuItem1',
click() {
console.log('item 1 clicked')
}
}))
menu.append(new MenuItem({type: 'separator'}))
menu.append(new MenuItem({label: 'MenuItem2', type: 'checkbox', checked: true}))
menu.append(new MenuItem ({
label: 'MenuItem3',
click() {
console.log('item 3 clicked')
}
}))
// Prevent default action of right click in chromium. Replace with our menu.
window.addEventListener('contextmenu', (e) => {
e.preventDefault()
menu.popup(remote.getCurrentWindow())
}, false)
</script>
Put this as first item in your HTML Body and it should work. At least it worked on my project
EDIT, cause I forgot it: Credits to google for answer on 6th entry

Can electron webview transform mouse event to touch event?

I want to simulate a mobile device in desktop environment. I can't find a argument to transform mouse event to touch event.
How can I approach this job? Any hint will be great. Thank you so much.
I think I figured it out. Dev environment:
node 7.4.0
Chromium 54.0.2840.101
Electron 1.5.1
const app = electron.app
const BrowserWindow = electron.BrowserWindow
let mainWindow;
function createWindow() {
mainWindow = new BrowserWindow({
width: 1024,
height: 768,
frame: false,
x: -1920,
y: 0,
autoHideMenuBar: true,
icon: 'assets/icons/win/app-win-icon.ico'
});
try {
// works with 1.1 too
mainWindow.webContents.debugger.attach('1.2')
} catch (err) {
console.log('Debugger attach failed: ', err)
}
const isDebuggerAttached = mainWindow.webContents.debugger.isAttached()
console.log('debugger attached? ', isDebuggerAttached)
mainWindow.webContents.debugger.on('detach', (event, reason) => {
console.log('Debugger detached due to: ', reason)
});
// This is where the magic happens!
mainWindow.webContents.debugger.sendCommand('Emulation.setTouchEmulationEnabled', {
enabled: true,
configuration: 'mobile',
});
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true,
show: false,
backgroundColor: '#8e24aa ',
}));
// Show the mainwindow when it is loaded and ready to show
mainWindow.once('ready-to-show', () => {
mainWindow.show()
})
}
// Listen for app to be ready
app.on('ready', createWindow);
Take a look at this Electron github issue or this Atom Discussion for ideas on how to get the touch working with Electron.
As far as how to approach it, I would look through the mouse events and touch events and just wire up a function that combines the Electron api and the relevant web api for mouse/touch.
Looking at the web-contents API, the only thing you can do is to open the dev tools with:
// win being a BrowserWindow object
win.webContents.openDevTools();
Then you will have to manually click on the responsive tools (the smartphone icon), and you will get into the mode you want.
But I am afraid there is no way to do it programatically. Mostly because it is considered as a development tool, and not a browser feature, so you will have the toolbar at the top and all these things. Not really something you want on Production.
You can try to use Microsoft Windows Simulator. You need to install Visual Studio 2019 with Universal Windows Platform development then run the simulator through:
C:\Program Files (x86)\Common Files\Microsoft Shared\Windows Simulator\16.0\Microsoft.Windows.Simulator.exe
I tested my electron app that also needs to run well both on touchscreen devices and devices without touch screen using this and it works really well to simulate touchscreen devices.
Do not forget to switch to touchscreen input on the right side of the panel, otherwise, the default input will simulate a mouse pointer.

How do I subscribe to a "window move" event in the Atom edtor?

I want to subscribe to the window moving event that electron provides, but I don't know how to code it in an atom package.
When I was reading the electron docs I found an example that I think is similar to what I want:
const {BrowserWindow} = require('electron')
let win = new BrowserWindow()
win.on('move', (e) => {
// . . .
})
But this appears to require creating a new electron window, and I don't know how to get the current BrowserWindow in an existing atom window.
I also can hook into the window.onresize event in atom, but there is no window.onmove.
Lastly, I found a way to get the window position in the atom docs, but I don't know how that would be useful without polling.
First, we should note that according to the official documentation, there are two events, move and moved. The latter is labeled as MacOS only.
In order to listen to the event need to fetch the current window. On the client side this can be done like this
const electron = require('electron');
const currentWindow = electron.remote.getCurrentWindow();
currentWindow.on('move', function() {
// Do move event action
});
On the application side there is no remote, so the window is fetched this way
const { BrowserWindow } = require('electron');
const currentWindow = BrowserWindow.getFocusedWindow();
currentWindow.on('move', function() {
// Do move event action
});

How to close a sidebar in firefox

I have a sidebar inside my firefox addon. I want the following behavior for this sidebar - I should force close the sidebar if it is open when the browser is being closed (so that the next time the browser is opened the sidebar is not in an open state). I am trying to do this:
uninit: function() {
var sidebarWindow = document.getElementById("sidebar").contentWindow;
if (sidebarWindow.location.href == "chrome://myaddon/content/mysidebar.xul") {
// Act on the sidebar content
toggleSidebar('mySampleSidebar');
}
}
I call this uninit for the window.unload event:
window.addEventListener("unload", function() { myobj.uninit()}, false);
Can someone tell me how to achieve this, as what I am trying to do is not working.
Thanks
Kapil
In your firefox sidebar overlay javascript add
toggleSidebar();
in the "load" event listener function.
See here for example:
sidebar.onFirefoxLoad = function(event) {
document.getElementById("contentAreaContextMenu")
.addEventListener("popupshowing", function (e)
{ sidebar.showFirefoxContextMenu(e); }, false);
toggleSidebar();
};
window.addEventListener("load", sidebar.onFirefoxLoad, false);
Your code is correct for closing your sidebar, but I think unload is too late to change the startup state of the browser window (browser.xul), because browser.xul has already been unloaded (and its state, including sidebar state, has already been stored away).
Instead use beforeunload. I tested the following and it seems to work fine:
window.addEventListener("unload", myobj.uninit, false)
On rare occasions the browser process could be killed so unload would not be called (user kills it or it crashes). I'm not sure if occasionally stores the state of the sidebar like it does tabs, but if it does it could open and have the sidebar visible in that rare case. To handle that case, you can add what #Vinothkumar suggested.
window.addEventListener("load", myobj.uninit, false)

Resources