browser window not receiving focus in electron - electron

this problem happen after i update dependency "electron": "^5.0.13" to "electron": "^12.0.6" before this it was working fine.
it is hard to say what is a problem so I am telling you how to recreate
press p (index.html mousetrap.js), it will open the print window(window 10)
after returning from the print window dialog, the browser window did not receive focus (i think) if I try to select text in the browser it highlight with gray color rather than blue (before press p when I select text it highlight with blue)
press p,w, etc... are not working
but press esc working
if I try to minimize the window and then maximize then it starts working normally (selected text turn blue again)
I check when main.js print code return
success => false
errorType => failed
window works fine but if it returns
success => false
errorType => cancelled
or return with
success => true
errorType =>
the window does not received focus
main.js
...
//for print
ipcMain.on('print-to', function (event) {
printWindow.webContents.print({},(success, errorType) => {
console.log("success => ",success)
console.log("errorType => ",errorType)
})
})
...
index.html
<html class="no-js" lang="">
<head>
<!-- Insert this line above script imports -->
<script>
if (typeof module === 'object') {
window.module = module;
module = undefined;
}
</script>
<!-- normal script imports etc -->
<script src="jquery-3.3.1.js" type="text/javascript"></script>
<!-- Insert this line after script imports -->
<script>
if (window.module) module = window.module;
</script>
<script>
const electron = require('electron');
const {
ipcRenderer
} = electron;
var Mousetrap = require('mousetrap');
function printFun() {
ipcRenderer.send('print-to');
}
Mousetrap.bind('w', function () {
alert("w press")
});
Mousetrap.bind('m', function () {
alert('m press')
});
Mousetrap.bind('esc', function () {
ipcRenderer.send('close', 'printWindow');
});
Mousetrap.bind('p', function () {
printFun();
});
</script>
</head>
<body id="preview">
kdjklsf
</body>
</html>
Dependencies
"electron": "^12.0.6",
I have no idea what to do! anyone suggest what is wrong and how to solve this problem
Thank you.

Related

How do I display console log in electron app

I'm currently creating a JS Desktop App using Electron. I'm able to get everything functional how I want it, but I want to be able to update the users on certain tasks and also display errors in the app itself.
Is there any way to add a section (terminal if you will) or something similar inside the UI, so I can log things out to the user?
Providing application feedback to your user is as simple as having a statusUpdate function in your main process send
a message (via your preload.js script) to your render process. Within your render process, listen for a message on the
assigned channel and once received, update the content of your DOM element.
main.js (main process)
// Import required electron modules
const electronApp = require('electron').app;
const electronBrowserWindow = require('electron').BrowserWindow;
// Import required Node modules
const nodePath = require('path');
// Prevent garbage collection
let window;
function createWindow() {
const window = new electronBrowserWindow({
x: 0,
y: 0,
width: 800,
height: 600,
show: false,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
preload: nodePath.join(__dirname, 'preload.js')
}
});
window.loadFile('index.html')
.then(() => { window.show(); });
return window;
}
electronApp.on('ready', () => {
window = createWindow();
statusTest();
});
electronApp.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
electronApp.quit();
}
});
electronApp.on('activate', () => {
if (electronBrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
// ---
function statusTest() {
let counter = 1;
let message;
setInterval(() => {
statusUpdate(`Status message ${counter} from main process.`);
counter++;
}, 1000);
}
function statusUpdate(message) {
window.webContents.send('statusMessage', message);
}
preload.js (main process)
// Import the necessary Electron modules
const contextBridge = require('electron').contextBridge;
const ipcRenderer = require('electron').ipcRenderer;
// Exposed protected methods in the render process
contextBridge.exposeInMainWorld(
// Allowed 'ipcRenderer' methods
'ipcRenderer', {
// From main to render
statusMessage: (message) => {
ipcRenderer.on('statusMessage', message);
}
}
);
index.html (render process)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Electron Test</title>
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';"/>
</head>
<body>
<label for="status">Status: </label>
<textarea id="status" cols="40" rows="10" disabled></textarea>
</body>
<script>
let status = document.getElementById('status');
window.ipcRenderer.statusMessage((event, message) => {
status.value += message + '\n'; // Append message
status.scrollTop = status.scrollHeight; // Show last entry
});
</script>
</html>

electronjs always refresh after clicking a button

I am using electron in building Desktop application when I am clicking on any button it make refresh for the whole application , I need to prevent this refresh
<script>
window.$ = window.jQuery = require('jquery')
$(function(){
var config = require('../jsonFiles/pathData.json');
$("#aspnetCorePathRename").val(config.AspnetCorePath);
$("#angularPathRename").val(config.AngularPath);
});
function ren(e) {
const fs = require("fs");
fs.readFile('./scrips/Rename.ps1', function (err, data) {
if (err) {
$(".Console").html(err.toString());
alert(err.toString());
return console.error(err);
}
alert(data.toString());
});
readFile();
}
</script>
That's most likely not a Problem of electron or your Script, but of the way you defined the buttons in your HTML. If you define it like this:
<input type="submit">
HTML assumes it's send button for a form and will refresh the page. If you define it as button
<button type='button'>Submit</button>
the page will not be refreshed.
If you have to define it as input I'd assume you prevent the default behaviour with jQuery like this:
$("input[type='submit']").click(function() { return false; });

console.log into devTools into Electron app and renderer process

Why my console.log doesn't display into devTools in my very simple electron app ?
I console.log into js file loaded by renderer process electron.
If I console.log into main process electron I can view the result into command line with no problem
I can see that the js file is loaded by the renderer process into devTools > network part. But nothing console.log wrote into devTools > Console part.
index.js :
const {app, BrowserWindow} = require('electron')
let win
function createWindow () {
win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
webSecurity: false
}
})
win.loadFile('index.html')
win.webContents.openDevTools()
console.log('main test')
win.on('closed', () => {
win = null
})
}
app.on('ready', createWindow)
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
if (win === null) {
createWindow()
}
})
process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true';
index.html file :
<h1>MAIN PAGE</h1>
<script type="javascript" src="midi-test.js"></script>
<button type="button">TEST</button>
midi-test.js file :
var navigator = require('jzz')
console.log('test')
if (navigator.requestMIDIAccess){
console.log('OK')
}
else{
console.log('KO')
}
I don't want to use electron-log npm package for writing console.log into OS file.
I don't want to redirect console.log renderer process to main process command-line.
Lot of questions about this issue but nothing simple response find.
In the index.html file, replace :
<script type="javascript" src="midi-test.js"></script>
With :
<script type="text/javascript" src="midi-test.js"></script>
Or :
<script src="midi-test.js"></script>
In fact javascript only is wrong

Electron - How to know when renderer window is ready

In my main process I create a renderer window:
var mainWindow = new BrowserWindow({
height: 600,
width: 800,
x: 0,
y: 0,
frame: false,
resizable: true
});
mainWindow.openDevTools();
mainWindow.loadURL('file://' + __dirname + '/renderer/index.html');
Then I want to communicate with it in some way:
mainWindow.webContents.send('message', 'hello world');
However the main window doesn't receive this message because it isn't fully done being created at the time I attempt to send it.
I have temporarily solved this by wrapping the latter code in a setTimeout() but that is most definitely not the right way to resolve a race condition.
Is there a callback for when the main window is ready? I tried the 'ready-to-show' event mentioned in the docs but it did not work.
A listener on "mainWindow" doesn't worked for me. I used instead "mainWindow.webContents".
mainWindow.webContents.once('dom-ready', () => {});
Have a look at the did-finish-load event mentioned in the Electron browser-window documentation.
mainWindow.once('did-finish-load', () => {
// Send Message
})
There seems to be a dom-ready event too.
not mentioned in the previous answers, loadURL returns a promise that resolves at the same time the 'did-finish-load' event is fired; i.e., they're essentially equivalent, except one's a promise, and the other's a callback.
Check this: https://github.com/electron/electron/blob/master/docs/api/web-contents.md
You can use this event to know if your windows is ready in you main.js [CASE 1], but if want to know when your page is full loaded you should add an event in your index.html [CASE 2] and then you can attach a function that send a message to his parent Main.js telling him, he is ready, using IPCrenderer and IPCmain
CASE 1
main.js:
mainWindows.webContents.on('did-finish-load',WindowsReady);
function WindowsReady() {
console.log('Ready');
}
CASE 2
html:
<script>
const {ipcRenderer} = require('electron');
document.addEventListener('DOMContentLoaded',pageLoaded);
function pageLoaded(){
alert('The page is loade');
ipcRenderer.send('Am_I_Ready',"Im ready");
}
</script>
Main.js:
const {ipcMain} = electron;
ipcMain.on('Am_I_Ready', doSomething)
function doSomething(){
console.log('Everything is ready.');
}
Use mainWindow.webContents like this:
mainWindow.webContents.on('did-finish-load', () => {
mainWindow.webContents.send('message', 'hello world');
}
I tried the following code in my app
window.webContents.once("did-finish-load", () => {
console.log("did-finish-load");
});
window.webContents.once("dom-ready", () => {
console.log("dom-ready");
});
window.once("ready-to-show", () => {
console.log("ready-to-show");
});
This is after loading an index.html from local file system:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Hi mom</title>
<script defer src="renderer.js"></script></head>
<body>
<div id="renderer"></div>
</body>
</html>
According to the console.log output they fired in the following sequence:
dom-ready
ready-to-show
did-finish-load
Therefore did-finish-load is probably the one to wait for -- because it's the latest therefore presumably the most-fully-loaded.
Also the API documentation for webContents.send includes this example:
// In the main process.
const { app, BrowserWindow } = require('electron')
let win = null
app.whenReady().then(() => {
win = new BrowserWindow({ width: 800, height: 600 })
win.loadURL(`file://${__dirname}/index.html`)
win.webContents.on('did-finish-load', () => {
win.webContents.send('ping', 'whoooooooh!')
})
})
If I remove the loading of an external script file ...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Hi mom</title>
<!-- <script defer src="renderer.js"></script> -->
</head>
<body>
<div id="renderer"></div>
</body>
</html>
... then the order of events is changed slightly ...
dom-ready
did-finish-load
ready-to-show
... which may explain why some of the other answers to this question contract each other.
These days, you use the "ready-to-show" event.
https://electronjs.org/docs/api/browser-window#using-ready-to-show-event

Prevent default on a click within a JQuery tabs in Google Chrome

I would like to prevent the default behaviour of a click on a link. I tried the return false; also javascript:void(0); in the href attribute but it doesn’t seem to work. It works fine in Firefox, but not in Chrome and IE.
I have a single tab that loads via AJAX the content which is a simple link.
<script type="text/javascript">
$(function() {
$("#tabs").tabs({
ajaxOptions: {
error: function(xhr, status, index, anchor) {
$(anchor.hash).html("Couldn't load this tab. We'll try to fix this as soon as possible. If this wouldn't be a demo.");
},
success: function() {
alert('hello');
$('#lk').click(function(event) {
alert('Click Me');
event.preventDefault();
return false;
});
}
},
load: function(event, ui) {
$('a', ui.panel).click(function(event) {
$(ui.panel).load(this.href);
event.preventDefault();
return false;
});
}
});
});
</script>
<body>
<div id="tabs">
<ul>
<li>Link</li>
</ul>
</div>
</body>
The content of linkChild.htm is
Click Me
So basically when the tab content is loaded with success, a click event is attached to the link “lk”. When I click on the link, the alert is displayed but then link disappears. I check the HTML and the element is actually removed from the DOM.
$('#selector').click(function(event) {
event.preventDefault();
});
The event object is passed to your click handler by default - you have to have something there to receive it. Once you have the event, you can use jQuery's .preventDefault() method to cancel the link's behavior.
Edit:
Here's the fragment of your code, corrected:
$('a', ui.panel).click(function(event) {
$(ui.panel).load(this.href);
event.preventDefault();
return false;
});
Notice the addition of the word 'event' when creating the anon function (or you could use just e, or anything else - the name is unimportant, the fact there's a var there is.

Resources