I am trying to create my own version of http://meetfranz.com/ using Electron.
The app should allow up multiple URLs such as https://messenger.com/ and https://gmail.com/ to be visible and have a tabbed interface.
I've tried both generating Webview and BrowserWindow.
WebView can't seem to load Messenger completely (does not load login)
BrowserWindow pops out of the main window…
I tried earlier on also with iFrames which was a no-go.
Any ideas on best way to accomplish a tabbed minimal browser interface that allows cookies/https?
index.html
<html>
<head>
<style>
webview {
display: inline-flex;
width: 800px;
height: 600px;
}
</style>
</head>
<body>
<form name="form">
<input name="input" placeholder="https://messenger.com/" value="https://messenger.com">
<button type="submit">submit</button>
</form>
<div class="tabs">
</div>
<div class="webviews">
</div>
<!--<webview src="https://messenger.com/" autosize="on" nodeintegration="on" disablewebsecurity="on" webpreferences="allowRunningInsecureContent"></webview>-->
<script type="text/javascript">
require('./app.js')
</script>
</body>
</html>
main.js
const {app, BrowserWindow, BrowserView} = require('electron')
app.on('ready', createWindow)
function createWindow(){
let win = new BrowserWindow({
width: 1000,
height: 600,
height: 600,
"node-integration": "iframe", // and this line
"web-preferences": {
"web-security": false,
"nodeIntegration": false,
}
})
win.on('closed', () => {
win = null
})
win.webContents.openDevTools()
// Load a remote URL
//win.loadURL('https://github.com')
// Or load a local HTML file
win.loadURL(`file://${__dirname}/index.html`)
/*win.webContents.session.webRequest.onHeadersReceived({}, (d, c) => {
if(d.responseHeaders['x-frame-options'] || d.responseHeaders['X-Frame-Options']){
delete d.responseHeaders['x-frame-options']
delete d.responseHeaders['X-Frame-Options']
}
c({cancel: false, responseHeaders: d.responseHeaders})
})*/
}
//app.commandLine.appendSwitch('disable-web-security')
app.js
const {app, BrowserWindow, BrowserView} = require('electron').remote
let tabs = document.querySelector(".tabs")
let webviews = document.querySelector(".webviews")
document.getElementsByTagName("form")[0].onsubmit = function(event){
//createWebview(form.input.value)
createBrowserWindow(form.input.value)
return false;
}
function createWebview(url){
let webview = new WebView()
webview.setAttribute("autosize","on")
webview.setAttribute("nodeintegration","on")
webview.setAttribute("disablewebsecurity","on")
webview.setAttribute("webpreferences","allowRunningInsecureContent")
webview.src = url
webviews.appendChild(webview)
let tab = document.createElement("div")
tab.textContent = url
tab.target = webview
tabs.appendChild(tab)
}
function createBrowserWindow(url){
let win = new BrowserWindow({
width: 800,
height: 600,
y: 100,
x: 100,
webPreferences: {
webSecurity: false,
nodeIntegration: false
}
})
win.setMenu(null)
win.on('closed', () => {
win = null
})
view = new BrowserView({
webPreferences: {
nodeIntegration: false
}
})
win.webContents.openDevTools()
// Load a remote URL
win.loadURL(url)
}
<webview> clearly is the way to if you want to have a single window. It's also a lot better than an <iframe>, because it's securely isolated from your app and runs in a separate process.
See the docs: https://electron.atom.io/docs/api/webview-tag/
If messenger.com doesn't load properly, this should be the problem you should be addressing (e.g. inspect console messages, network log). Follow your instincts, your first choice was the right one, now it's about making it work.
Related
So far I build a simple Electron application. My problem is the input.focus() is not working on displaying an alert box. I tried to solve the problem, and I came up with a solution: when I minimize and maximize the window, the input.focus() is working well. So when I try to show an alert box, the input.focus() isn't working, except minimize and maximizing. I try to open the code in Chrome, and all functionalities are working very well, so the problem is in the Electron renderer.
Before minimizing and maximizing the window
After minimizing and maximizing the window
My Electron renderer
const path = require("path");
const { app, BrowserWindow } = require("electron");
const createWindow = () => {
const win = new BrowserWindow({
width: 780,
height: 600,
minWidth: 780,
minHeight: 600,
icon: path.join(__dirname, "assets/favicon.ico"),
webPreferences: {},
});
win.maximize();
// win.removeMenu();
win.loadFile("index.html");
};
app.whenReady().then(() => {
createWindow();
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0)
createWindow();
});
});
app.on("window-all-closed", () => {
if (process.platform !== "darwin")
app.quit();
});
The Input focus will lose if the app window not focused.
When you minimize and maximize the app window the input focus come back.
And When you send alert box the alert open in another window so the main app window blur and its input focus blur.
I have a list. Click one item and then pop-up window which is named open. It's focused when it first opens, but it's out of focus the second time.
enter image description here
when I click a button, the following code execute. But, winObj.focus() not working in electron. It's only focus the main window. How do I fix it?
chatList.js (build in react)
const onClickBtn = useCallback(
(chat) => {
const winObj = window.open(
`/chatting/${chat.url}`,
chat.url,
"",
true
);
winObj.focus();
},
[]
);
electron.js (same as public/main.js)
function createWindow() {
const win = new BrowserWindow({
width: 400,
height: 700,
webPreferences: {
nodeIntegration: true,
nativeWindowOpen: true,
preload: path.join(__dirname, "/../build/preload.js"),
},
});
const pubUrl = "https://---";
win.loadURL(pubUrl);
//when i click the button above, the event come into here.
win.webContents.setWindowOpenHandler((event) => {
return {
action: "allow",
overrideBrowserWindowOptions: {
...win.webContents.browserWindowOptions,
parent: win,
},
};
});
}
This is an existing bug with Electron.
win.focus() will not actually focus the BrowserWindow. You'll want to send an ipc message down to the main process, grab your BrowserWindow and call win.focus() from there.
I'm making an app using Electron framework and I tried using buttons to close and minimize the window. I've tried multiple things for it to do this but without success.
This is what I have for the moment:
HTML:
<body>
<!-- Titlebar -->
<button id="minimize-button">-</button>
<button id="close-button">x</button>
<!-- Script -->
<script src="./js/minimize-close.js"></script>
</body>
JS (minimize-close.js):
const { ipcRenderer } = require('electron');
document.getElementById("minimize-button").addEventListener('click', () => {
ipcRenderer.send('minimize-window');
});
document.getElementById("close-button").addEventListener('click', () => {
ipcRenderer.send('close-window');
});
JS (index.js):
const { app, BrowserWindow, ipcMain } = require('electron');
function createWindow(){
const window = new BrowserWindow({
width: 960, height: 580,
resizable: false, maximizable: false,
frame: false, autoHideMenuBar: true,
icon: './icon.ico',
webPreferences: {
nodeIntegration: true,
devTools: false
}
});
window.loadFile('./src/index.html');
}
// Minimize and close window
ipcMain.on('minimize-window', () => {
window.minimize();
});
ipcMain.on('close-window', () => {
window.close();
});
app.whenReady().then(() => {
createWindow();
app.on('activate', function(){
if(BrowserWindow.getAllWindows().length === 0){
createWindow();
}
});
});
app.on('window-all-closed', function(){
if(process.platform !== 'darwin'){
app.quit();
}
});
You need to set contextIsolation: false.
Also I have read around that window must be global. If not at some point it will be collected by the garbage collector because function which created it has already finished.
let window;
function createWindow(){
window = new BrowserWindow({
width: 960, height: 580,
resizable: false, maximizable: false,
frame: false, autoHideMenuBar: true,
icon: './icon.ico',
webPreferences: {
nodeIntegration: true,
// devTools: false, // commented for debugging purposes
contextIsolation: false
}
});
window.loadFile('./src/index.html');
window.webContents.openDevTools(); // Open dev tools to see if any error arised. In this case I saw 'require is not defined' before setting contextIsolation. Remove it when going into production.
}
Option B: more "secure"
If security is a concern and you want nodeIntegration and contextIsolation to retain their default secure values then preload.js scheme is needed.
This should be the case if remote content is loaded by your App.
HTML
<body>
<!-- Titlebar -->
<button id="minimize-button">-</button>
<button id="close-button">x</button>
</body>
preload.js
const { ipcRenderer } = require('electron');
window.addEventListener('DOMContentLoaded', () => {
document.getElementById("minimize-button").addEventListener('click', () => {
ipcRenderer.send('minimize-window');
});
document.getElementById("close-button").addEventListener('click', () => {
ipcRenderer.send('close-window');
});
})
index.js
const path = require('path');
function createWindow(){
window = new BrowserWindow({
width: 960, height: 580,
resizable: false, maximizable: false,
frame: false, autoHideMenuBar: true,
icon: './icon.ico',
webPreferences: {
// devTools: false, // commented for debugging purposes
preload: path.join(__dirname, 'preload.js')
}
});
window.loadFile('./src/index.html');
window.webContents.openDevTools(); // Open dev tools to see if any error arised. In this case I saw 'require is not defined' before setting contextIsolation. Remove it when going into production.
}
I need to reload my site/app after network re-connect. So, I'm using win.reload after reconnect but after reloading it shows me a blank white screen
I have tried to re-create the window but it gives me the same output. Another question reported here by me.
I found window.location.href is set to "chrome-error://chromewebdata/" after reload
This sample code from is main.js
let mainWindow = null;
let offlineWindow = null;
let loadingwindow = null;
let mainWindowWidth = 1100;
let mainWindowHeight = 650;
var nativeApp = {
appUrl: "https://google.com",
connected: false
}
function createWindow () {
// Create the browser window.
mainWindow = new BrowserWindow({
webPreferences: {
nodeIntegration: false,
preload: path.join(app.getAppPath(), 'preload.js')
},
minWidth: mainWindowWidth,
width: mainWindowWidth,
minHeight: mainWindowHeight,
height: mainWindowHeight,
show: false
});
createLoadingWindow();
mainWindow.once('ready-to-show', () => {
closeLoadingWindow();
mainWindow.show();
});
mainWindow.setMenu(null);
mainWindow.loadURL(nativeApp.appUrl);
mainWindow.webContents.openDevTools();
}
function createLoadingWindow(){
// codes to create the loading window
// .....
}
function createOfflineWindow(){
// codes to create the offline window
//....
}
function checkAndConnect() {
checkInternet(function (connected) {
if (!connected) {
if (!offlineWindow) { createOfflineWindow(); }
} else {
if (offlineWindow) {
offlineWindow.close();
mainWindow.reload();
}
}
nativeApp.connected = connected;
});
}
function checkInternet(callback) {
if(navigator.onLine){
return callback(true);
}
return callback(false);
}
I need to reload my site/app after re-connection. Is there anything wrong in my code? or is it a bug by the electron?
It's an old thread, but if someone comes across the same problem, you can fix it by adding the following in the main js file:
function createMainWindow () {
mainWindow = new BrowserWindow({
width: 1280,
height: 720,
...
})
// This code block is not related to the issue
// I included it to demostrate how my app loads the index page
if (process.env.WEBPACK_DEV_SERVER_URL) {
if (!process.env.IS_TEST) {
mainWindow.webContents.openDevTools()
}
}
else {
createProtocol('app')
mainWindow.loadURL('app://./index.html')
}
// Create listener that will handle the white screen issue
mainWindow.webContents.on('did-fail-load', () => {
if (process.env.NODE_ENV === 'production') {
// Load the index URL the same way you load it above
mainWindow.loadURL('app://./index.html')
}
})
...
In Electron I want to trigger a javascript function in a browser window when that browser window is shown.
The code I have at the moment is as follows:
main.js (Main Process)
myWin = new BrowserWindow({ width: 1200, height: 400, show: false })
.... some time later and under certain circumstances ;-) ....
myWin.show()
usbUpload.js (Browser Window)
function validateFlights() {
...blar...
}
this.addEventListener('onshow', () => {
validateFlights()
})
ValidateFlights() is the function in the browser window that I want to execute when the browser window is shown.
Any ideas?
You can directly call javascript in the renderer process from main process using executeJavaScript. Combined with 'show' event of BrowserWindow you can do the following:
myWin.on('show', () => {
myWin.webContents.executeJavaScript('validateFlights()')
})
Example:
main.js
const { app, BrowserWindow } = require('electron')
const path = require('path')
app.once('ready', () => {
let win = new BrowserWindow({show: false})
win.once('show', () => {
win.webContents.executeJavaScript('validateFlights()')
})
win.loadURL(path.resolve(__dirname, 'index.html'))
win.show()
})
index.html
<html>
<head>
<script type="text/javascript">
function validateFlights() {
console.log('validated')
}
</script>
</head>
<body></body>
</html>
In your main process you probably want to do something with win.show() and the focus event if your window is already open in the background. Something like so:
let win = new BrowserWindow({width: 800, height: 600})
win.on('onFocus', () => {
win.show()
})