Is there a way to fake the Document.visibilityState
on an electron app? I need that for a website that doesn't correctly deal with losing focus (it only looks at Document.visibilityState
and should be looking at blur also).
Minimizing the window works, but is not convenient.
EDIT: my use case is: I'm wrapping a website in an electron app. That website is looking at Document.visibilityState
to know if the user is active or not. The problem is that if the user switches to another window, the visibilityState is still "visible". The site should also be looking at the blur/focus events, but it is not (it is not my website). I would like to handle the blur event myself (which I can), and fake the Document.visibilityState
so knows that it is not visible or focused.
You can use a script resembling the one below to override the values:
> document.__defineGetter__("visibilityState", function() { return "tarun";})
undefined
> document.visibilityState
"tarun"
Now, the main thing is for you to determine how to you want to change the value. Shown below is how you can interact with the web page:
const electron = require('electron')
// Importing BrowserWindow from Main Process using Electron remote
const BrowserWindow = electron.remote.BrowserWindow;
var inject = document.getElementById('inject');
let win = BrowserWindow.getFocusedWindow();
// let win = BrowserWindow.getAllWindows()[0];
inject.addEventListener('click', (event) => {
win.webContents.executeJavaScript('const path = require("path");'
+ 'const fs = require("fs");'
+ 'fs.readFile(path.join(__dirname, "../assets/sample.txt"), '
+ '{encoding: "utf-8"}, function(err, data) {'
+ 'if (!err) { console.log("received data: " + data); }'
+ 'else { console.log(err); } });', true)
.then(console.log('JavaScript Executed Successfully'));
});
var print = document.getElementById('print');
print.addEventListener('click', (event) => {
var webSource = {
code: 'var numbers = [1, 2, 3, 4, 5];'
+ 'function filters(num) { return num > 2; }'
+ 'console.log(numbers.filter(filters));',
url: '',
startLine: 1
}
win.webContents.executeJavaScriptInIsolatedWorld(1, [webSource], true)
.then(console.log('JavaScript Executed Successfully'));
});
PS: The above code is found at https://www.geeksforgeeks.org/dynamically-execute-javascript-in-electronjs/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With