I'm loading a window from data-uri:
pref.loadURL('data:text/html;charset=utf-8,' + encodeURI(str), { baseURLForDataURL: 'file://' + app.getAppPath() } );
The good news is that the dev tools console shows errors now for the css/js files that should be loading but aren't, but I can't make sense of what it expects. There are no examples anywhere, not even in the github issues that inspired this option.
Does it expect an absolute path (as in my example above)?
It would normally expect
'file://' + app.getAppPath().replace("\\", "/") + "/"
But at the moment, there seem to be an issue where at least when using the protocol 'file://' we get an error. (https://github.com/electron/electron/issues/20700)
One way of going around this issue is by generating a custom file protocol.
const { app, BrowserWindow, screen, protocol } = require('electron');
const path = require('path');
app.on('ready', () => {
const customProtocol = 'file2';
protocol.registerFileProtocol(customProtocol, (request, callback) => {
const url = request.url.substr(customProtocol.length + 2);
const file = { path: path.normalize(`${__dirname}/${url}`) }
callback(file)
});
let win = new BrowserWindow({
webPreferences: {
nodeIntegration: true,
contextIsolation: true
}
});
win.loadURL(`data:text/html;charset=UTF-8,${encodeURIComponent(indexHTML)}`, {
baseURLForDataURL: `${customProtocol}://${app.getAppPath().replace("\\", "/")}/`
});
});
Related
My electron main.js code:
function createWindow () {
const { screen } = require('electron');
const primaryDisplay = screen.getPrimaryDisplay();
const { width, height } = primaryDisplay.workAreaSize;
let mainWindow = new BrowserWindow({
width,
height,
webPreferences: {
webSecurity: false,
},
});
return mainWindow;
}
function createServerProcess () {
serverProcess = fork(__dirname + '/index.js');
}
app.whenReady().then(async () => {
createServerProcess();
let mainWindow = createWindow();
let workspaceId = await localStorage.getItem('workspaceId');
if (!workspaceId) {
workspaceId = 'abc';
}
let url = `http://${workspaceId}.localhost:8443`;
setTimeout(() => {
mainWindow.loadURL(url);
}, 3000);
});
I am using electron-forge to build my electron app, using electron-forge start to start local app works fine. But when starting the app generated by electron-forge make command, it shows below error:
I have already set webSecurity to false, for turning off cross origin restriction. Just don't know why while local app works fine but generated app is not working. I am confused. I am new to Electron.
I have an electron application that loads a web page on the internet.
one of the sites main features is the ability to capture screen, it uses the
navigator.mediaDevices.getDisplayMedia({video: true});
but obviously, the electron will through the Permission denied because there will be no 'selecting window to capture' popped up to grant any permission to it.
I already check out some articles and saw desktopCapture
the problem is, this is happening and running through the web page javascript not my application's code so I don't know how to affect it.
so what should I do to make capturing the screen works in this situation?
You can override navigator.mediaDevices.getDisplayMedia to call Electron's desktopCapturer API like shown below. This implementation assumes you have contextIsolation enabled which is the default behaviour in Electron >= 12
// preload.js
const { desktopCapturer, contextBridge } = require("electron");
const { readFileSync } = require("fs");
const { join } = require("path");
// inject renderer.js into the web page
window.addEventListener("DOMContentLoaded", () => {
const rendererScript = document.createElement("script");
rendererScript.text = readFileSync(join(__dirname, "renderer.js"), "utf8");
document.body.appendChild(rendererScript);
});
contextBridge.exposeInMainWorld("myCustomGetDisplayMedia", async () => {
const sources = await desktopCapturer.getSources({
types: ["window", "screen"],
});
// you should create some kind of UI to prompt the user
// to select the correct source like Google Chrome does
const selectedSource = sources[0]; // this is just for testing purposes
return selectedSource;
});
// renderer.js
navigator.mediaDevices.getDisplayMedia = async () => {
const selectedSource = await globalThis.myCustomGetDisplayMedia();
// create MediaStream
const stream = await navigator.mediaDevices.getUserMedia({
audio: false,
video: {
mandatory: {
chromeMediaSource: "desktop",
chromeMediaSourceId: selectedSource.id,
minWidth: 1280,
maxWidth: 1280,
minHeight: 720,
maxHeight: 720,
},
},
});
return stream;
};
Now when this API is called, a stream will be returned to the caller as expected
navigator.mediaDevices.getDisplayMedia({video: true});
I have created a GitHub repo that has a working implementation of this solution
I'm working on a JHipster application that I'm trying to get functioning in Electron. I have Golden Layout for window/pane management and cross-pane communication. I am having several problems with the combination of technologies, including:
I can't pop out more than one pane at the same time into their own Electron windows. I instead get an Uncaught Error: Can't create config, layout not yet initialised error in the console.
Two thirds of the panes don't display anything when popped out into Electron windows, and I'm not sure what the reason is. Any ideas or suggestions for this? One example of content is a leaflet map, another is a "PowerPoint preview" that is really just divs that mock the appearance of slides.
I haven't made it this far yet, but I assume that I will have trouble communicating between popped-out Electron windows when I get more than one open. Right now, the panes communicate between each other using Golden Layout's glEventHub emissions. I have an avenue to explore when I cross that bridge, namely Electron ipcRenderer.
Some borrowed code is here (most of it I can't share because it's company confidential):
electron.js:
const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
const path = require('path');
const isDev = require('electron-is-dev');
let mainWindow;
function createWindow() {
mainWindow = new BrowserWindow({width: 900, height: 680});
mainWindow.loadURL(isDev ? 'http://localhost:9000' : `file://${path.join(__dirname, '../build/index.html')}`);
if (isDev) {
// Open the DevTools.
//BrowserWindow.addDevToolsExtension('<location to your react chrome extension>');
mainWindow.webContents.openDevTools();
}
mainWindow.on('closed', () => mainWindow = null);
}
app.on('ready', createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (mainWindow === null) {
createWindow();
}
});
goldenLayoutComponent.tsx, a patch for Golden Layout:
import React from "react";
import ReactDOM from "react-dom";
// import "./goldenLayout-dependencies";
import GoldenLayout from "golden-layout";
import "golden-layout/src/css/goldenlayout-base.css";
import "golden-layout/src/css/goldenlayout-dark-theme.css";
import $ from "jquery";
interface IGoldenLayoutProps {
htmlAttrs: {},
config: any,
registerComponents: Function
}
interface IGoldenLayoutState {
renderPanels: Set<any>
}
interface IContainerRef {
current: any
}
export class GoldenLayoutComponent extends React.Component <IGoldenLayoutProps, IGoldenLayoutState> {
goldenLayoutInstance = undefined;
state = {
renderPanels: new Set<any>()
};
containerRef: IContainerRef = React.createRef();
render() {
const panels = Array.from(this.state.renderPanels || []);
return (
<div ref={this.containerRef as any} {...this.props.htmlAttrs}>
{panels.map((panel, index) => {
return ReactDOM.createPortal(
panel._getReactComponent(),
panel._container.getElement()[0]
);
})}
</div>
);
}
componentRender(reactComponentHandler) {
this.setState(state => {
const newRenderPanels = new Set(state.renderPanels);
newRenderPanels.add(reactComponentHandler);
return { renderPanels: newRenderPanels };
});
}
componentDestroy(reactComponentHandler) {
this.setState(state => {
const newRenderPanels = new Set(state.renderPanels);
newRenderPanels.delete(reactComponentHandler);
return { renderPanels: newRenderPanels };
});
}
componentDidMount() {
this.goldenLayoutInstance = new GoldenLayout(
this.props.config || {},
this.containerRef.current
);
if (this.props.registerComponents instanceof Function)
this.props.registerComponents(this.goldenLayoutInstance);
this.goldenLayoutInstance.reactContainer = this;
this.goldenLayoutInstance.init();
}
}
// Patching internal GoldenLayout.__lm.utils.ReactComponentHandler:
const ReactComponentHandler = GoldenLayout["__lm"].utils.ReactComponentHandler;
class ReactComponentHandlerPatched extends ReactComponentHandler {
_container: any;
_reactClass: any;
_render() {
const reactContainer = this._container.layoutManager.reactContainer; // Instance of GoldenLayoutComponent class
if (reactContainer && reactContainer.componentRender)
reactContainer.componentRender(this);
}
_destroy() {
// ReactDOM.unmountComponentAtNode( this._container.getElement()[ 0 ] );
this._container.off("open", this._render, this);
this._container.off("destroy", this._destroy, this);
}
_getReactComponent() {
// the following method is absolute copy of the original, provided to prevent depenency on window.React
const defaultProps = {
glEventHub: this._container.layoutManager.eventHub,
glContainer: this._container
};
const props = $.extend(defaultProps, this._container._config.props);
return React.createElement(this._reactClass, props);
}
}
GoldenLayout["__lm"].utils.ReactComponentHandler = ReactComponentHandlerPatched;
Any help or insight into these issues would be appreciated. Thanks in advance!
If you are still looking for a solutions, 1 and 2 I have solved, if you want to see my solution you could see in this repository.
But it was basically this:
1: The window that popups has a different path than the main window, so I just had to put a try catch in my requires, and you have to set
nativeWindowOpen = true
when creating the Browser window.
2: Solves it's self after 1 I think
I've got an Electron app that shows a tray icon, which, when clicked, shows my main window. works great in development mode, but when I package it, (into a .app file), and double click the .app file, none of the menus show up, and more importantly, the icon doesn't show up, and so the user can never see my app.
I'm using the electron React/Redux Boilerplate (https://github.com/chentsulin/electron-react-boilerplate)
here's my main.dev.js file - any guesses are appreciated:
import { app, BrowserWindow, Tray } from 'electron';
import MenuBuilder from './menu';
let mainWindow = null;
let tray;
if (process.env.NODE_ENV === 'production') {
const sourceMapSupport = require('source-map-support');
sourceMapSupport.install();
}
if (
process.env.NODE_ENV === 'development' ||
process.env.DEBUG_PROD === 'true'
) {
require('electron-debug')();
const path = require('path');
const p = path.join(__dirname, '..', 'app', 'node_modules');
require('module').globalPaths.push(p);
}
const installExtensions = async () => {
const installer = require('electron-devtools-installer');
const forceDownload = !!process.env.UPGRADE_EXTENSIONS;
const extensions = ['REACT_DEVELOPER_TOOLS', 'REDUX_DEVTOOLS'];
return Promise.all(
extensions.map(name => installer.default(installer[name], forceDownload))
).catch(console.error);
};
/**
* Add event listeners...
*/
app.on('window-all-closed', () => {
// Respect the OSX convention of having the application in memory even
// after all windows have been closed
if (process.platform !== 'darwin') {
app.quit();
}
});
const getWindowPosition = () => {
const windowBounds = mainWindow.getBounds();
const trayBounds = tray.getBounds();
// Center window horizontally below the tray icon
const x = Math.round(
trayBounds.x + trayBounds.width / 2 - windowBounds.width / 2
);
// Position window 4 pixels vertically below the tray icon
const y = Math.round(trayBounds.y + trayBounds.height + 4);
return { x, y };
};
function createTray() {
const path = require('path');
const iconPath = path.join(__dirname, 'confluence.png');
tray = new Tray(iconPath);
tray.setToolTip('Confluence Helper');
tray.on('click', event => {
toggleWindow();
// Show devtools when command clicked
if (mainWindow.isVisible() && process.defaultApp && event.metaKey) {
mainWindow.openDevTools({ mode: 'detach' });
}
});
}
const toggleWindow = () => {
if (mainWindow.isVisible()) {
mainWindow.hide();
} else {
showWindow();
}
};
const showWindow = () => {
const position = getWindowPosition();
mainWindow.setPosition(position.x, position.y, false);
mainWindow.show();
mainWindow.focus();
};
app.on('ready', async () => {
if (
process.env.NODE_ENV === 'development' ||
process.env.DEBUG_PROD === 'true'
) {
await installExtensions();
}
mainWindow = new BrowserWindow({
show: false,
width: 500,
height: 728,
icon: `${__dirname}/confluence.icns`
});
mainWindow.loadURL(`file://${__dirname}/app.html`);
createTray();
// #TODO: Use 'ready-to-show' event
// https://github.com/electron/electron/blob/master/docs/api/browser-window.md#using-ready-to-show-event
mainWindow.webContents.on('did-finish-load', () => {
if (!mainWindow) {
throw new Error('"mainWindow" is not defined');
}
if (process.env.START_MINIMIZED) {
mainWindow.minimize();
}
});
mainWindow.on('blur', () => {
mainWindow.hide();
});
mainWindow.on('closed', () => {
mainWindow = null;
});
const menuBuilder = new MenuBuilder(mainWindow);
menuBuilder.buildMenu();
});
When i right clicked the .app file, and chose "Show Package Contents", I could see a Contents/Mac folder, and inside that was a unix executable file, which when I ran in the command line, showed me a rejected promised that had to do with my tray icon - I was doing a path.join(__dirname,'icon.png'), that ended up being the wrong path (console.log(path.join(__dirname,'icon.png')) to the rescue!
When I changed that to an absolute path ('users/myname/app/icon.png') and rebuilt, it worked!
However, this obviously won't work on OTHER people's computers - it did work on my computer(tm), but that's not good enough.
To REALLY fix it, I might have gone overboard - but this is what worked for me - by creating a NativeImage, using a path.join(__dirname,'resources','icon.png') in what I passed into that. I also added resources under build/files in package.json.
If you run into this kind of problem, i would recommend doing what I did (show package contents, etc) to see the issue in the packaged electron app.
I had the same problem on Windows (didn't tested in other OSes). Tray icon was working when running the app from VSCode, but it was invisible after packaged for Windows. Like the answer from #raingod, I was using the absolute path:
//Gets the icon to use in the tray
icon = nativeImage.createFromPath(path.join(__dirname, "build", "32x32.png"))
//Creates the tray
tray = new Tray(icon)
But what I found to be the problem was that I was pointing to a file in the "build" folder, where all the icons for my app were stored. Somehow it was causing this problem with the tray icon in the packaged app specifically. So I moved just the file used in the tray icon to another folder: "./src/icons/32x32.png". So the code looked like this:
//Gets the icon to use in the tray
icon = nativeImage.createFromPath(path.join(__dirname, "src", "icons", "32x32.png"))
//Creates the tray
tray = new Tray(icon)
Posting this here because another person might have the same problem. So use absolute path, and don't store the icon file in the "build" folder.
I'm attempting to implement windows auto update functionality in an electron app (which may lead to my early death) and I'm getting this error.
This is the URL I'm passing for testing purposes
EDIT: my electron app is using the two package.json structure and this code is in my app>main.js file
const feedURL = 'C:\\Users\\p00009970\\Desktop\\update_test';
autoUpdater.setFeedURL(feedURL);
autoUpdater.checkForUpdates();
EDIT2: Thanks to #JuanMa, I was able to get it working. Here is the code.
// auto update functionality
const {autoUpdater} = require('electron')
// local file system example: const feedURL = 'C:\\Users\\john\\Desktop\\updates_folder';
// network file system example: const feedURL = '\\\\serverName\\updates_folder';
const feedURL = '\\\\serverName\\updates_folder';
app.on('ready', () => {
autoUpdater.setFeedURL(feedURL);
// auto update event listeners, these are fired as a result of autoUpdater.checkForUpdates();
autoUpdater.addListener("update-available", function(event) {
});
autoUpdater.addListener("update-downloaded", function(event, releaseNotes, releaseName, releaseDate, updateURL) {
//TODO: finess this a tad, as is after a few seconds of launching the app it will close without warning
// and reopen with the update which could confuse the user and possibly cause loss of work
autoUpdater.quitAndInstall();
});
autoUpdater.addListener("error", function(error) {
});
autoUpdater.addListener("checking-for-update", function(event) {
});
autoUpdater.addListener("update-not-available", function(event) {
});
// tell squirrel to check for updates
autoUpdater.checkForUpdates();
})
Are you including the autoUpdater module correctly?
const {autoUpdater} = require('electron')
If so try to execute the code after the app 'ready' event.
app.on('ready', () => {
const feedURL = 'C:\\Users\\p00009970\\Desktop\\update_test';
autoUpdater.setFeedURL(feedURL);
autoUpdater.checkForUpdates();
})