feat: enhance WebContents and BrowserWindow with navigation and devtools features

- Added history management to WebContents for back and forward navigation.
- Implemented methods for opening, closing, and toggling devtools in WebContents and BrowserWindow.
- Introduced capturePage and printToPDF methods in WebContents for screenshot and PDF generation.
- Added process polyfill for WebView-only mode to ensure compatibility without a Node.js runtime.
- Updated native bridge to handle new window management commands.
- Enhanced Cargo.toml and Cargo.lock for dependency alignment.
- Updated package-lock.json for versioning consistency across native installers.
This commit is contained in:
miles committed 2026-09-18 11:31:55 -05:00
1 parent f45e458c53
commit 06b14e6cda
11 files changed
+854 -42

No files matched your search

+151 -14
View File
@@ -21,6 +21,9 @@ class WebContents extends EventEmitter {
this._zoomLevel = 0;
this._userAgent = '';
this._audioMuted = false;
this._isDevToolsOpened = false;
this._history = [];
this._historyIndex = -1;
}
get URL() { return this._url; }
@@ -53,8 +56,10 @@ class WebContents extends EventEmitter {
loadURL(targetUrl) {
this._url = targetUrl;
this._pushHistory(targetUrl);
this._isLoading = true;
this.emit('did-start-loading');
this.emit('did-start-navigation', targetUrl);
if (isNative) {
bridge.loadUrl(this.id, targetUrl);
}
@@ -62,6 +67,7 @@ class WebContents extends EventEmitter {
this._isLoading = false;
this.emit('did-stop-loading');
this.emit('did-finish-load');
this.emit('did-navigate', targetUrl);
this.emit('dom-ready');
}, isNative ? 500 : 100);
return Promise.resolve();
@@ -70,8 +76,10 @@ class WebContents extends EventEmitter {
loadFile(filePath) {
const url = `file://${path.resolve(filePath)}`;
this._url = url;
this._pushHistory(url);
this._isLoading = true;
this.emit('did-start-loading');
this.emit('did-start-navigation', url);
if (isNative) {
bridge.loadFile(this.id, filePath);
}
@@ -79,6 +87,7 @@ class WebContents extends EventEmitter {
this._isLoading = false;
this.emit('did-stop-loading');
this.emit('did-finish-load');
this.emit('did-navigate', url);
this.emit('dom-ready');
}, isNative ? 500 : 100);
return Promise.resolve();
@@ -87,6 +96,7 @@ class WebContents extends EventEmitter {
reload() {
this._isLoading = true;
this.emit('did-start-loading');
this.emit('did-start-navigation', this._url);
if (isNative && this._url) {
bridge.loadUrl(this.id, this._url);
}
@@ -94,14 +104,70 @@ class WebContents extends EventEmitter {
this._isLoading = false;
this.emit('did-stop-loading');
this.emit('did-finish-load');
this.emit('did-navigate', this._url);
}, 50);
return Promise.resolve();
}
canGoBack() { return false; }
canGoForward() { return false; }
goBack() {}
goForward() {}
reloadIgnoringCache() {
return this.reload();
}
goBack() {
if (!this.canGoBack()) return Promise.resolve();
this._historyIndex -= 1;
const url = this._history[this._historyIndex];
this._url = url;
this._isLoading = true;
this.emit('did-start-loading');
this.emit('did-start-navigation', url);
if (isNative) bridge.goBack(this.id);
setTimeout(() => {
this._isLoading = false;
this.emit('did-stop-loading');
this.emit('did-finish-load');
this.emit('did-navigate', url);
}, 50);
return Promise.resolve();
}
goForward() {
if (!this.canGoForward()) return Promise.resolve();
this._historyIndex += 1;
const url = this._history[this._historyIndex];
this._url = url;
this._isLoading = true;
this.emit('did-start-loading');
this.emit('did-start-navigation', url);
if (isNative) bridge.goForward(this.id);
setTimeout(() => {
this._isLoading = false;
this.emit('did-stop-loading');
this.emit('did-finish-load');
this.emit('did-navigate', url);
}, 50);
return Promise.resolve();
}
canGoBack() { return this._historyIndex > 0; }
canGoForward() { return this._historyIndex >= 0 && this._historyIndex < this._history.length - 1; }
_pushHistory(url) {
if (!url) return;
if (this._history[this._historyIndex] === url) return;
this._history = this._history.slice(0, this._historyIndex + 1);
this._history.push(url);
this._historyIndex = this._history.length - 1;
}
getURL() { return this._url; }
getTitle() { return this._title; }
getHistory() { return this._history.slice(); }
stop() {
this._isLoading = false;
this.emit('did-stop-loading');
}
executeJavaScript(code, userGesture = true) {
if (isNative) {
@@ -132,11 +198,27 @@ class WebContents extends EventEmitter {
setAudioMuted(muted) { this._audioMuted = muted; }
isAudioMuted() { return this._audioMuted; }
openDevTools() { console.log('[gelectron] openDevTools'); }
closeDevTools() {}
isDevToolsOpened() { return false; }
toggleDevTools() {}
inspectElement() {}
openDevTools(options) {
if (this._isDevToolsOpened) return;
this._isDevToolsOpened = true;
this.emit('devtools-opened');
if (isNative) bridge.openDevTools(this.id);
}
closeDevTools() {
if (!this._isDevToolsOpened) return;
this._isDevToolsOpened = false;
this.emit('devtools-closed');
if (isNative) bridge.closeDevTools(this.id);
}
toggleDevTools() {
if (this._isDevToolsOpened) this.closeDevTools();
else this.openDevTools();
}
isDevToolsOpened() { return this._isDevToolsOpened; }
inspectElement(x, y) {
if (isNative) bridge.inspectElement(this.id, x || 0, y || 0);
}
inspectServiceWorker() {}
setIgnoreMenuShortcuts() {}
setWindowOpenHandler() { return { action: 'deny' }; }
@@ -144,7 +226,51 @@ class WebContents extends EventEmitter {
setCertificateVerifyProc() {}
setBackgroundColor() {}
isCrashed() { return false; }
capturePage() { return Promise.resolve(null); }
capturePage(rect) {
if (isNative) {
return bridge.capturePage(this.id).then((result) => {
if (result && result.data && typeof result.data === 'string' && result.data.length > 0) {
return NativeImage.createFromDataURL(`data:image/png;base64,${result.data}`);
}
return NativeImage.createEmpty();
}).catch(() => NativeImage.createEmpty());
}
// Without a native runtime there is nothing to snapshot; return an empty
// NativeImage (matching Electron's behaviour for unavailable images) so
// callers that guard on image.isEmpty() do not crash.
return Promise.resolve(NativeImage.createEmpty());
}
print(options, callback) {
if (typeof options === 'function') { callback = options; options = {}; }
if (isNative) {
bridge.printPage(this.id);
} else {
console.log('[gelectron] print called');
}
if (typeof callback === 'function') {
// Node emulates `callback` after the print dialog closes; a false result
// means no failure was reported.
process.nextTick(callback, false);
}
return undefined;
}
printToPDF(options) {
const opts = Object.assign({}, options || {});
if (isNative) {
return bridge.printToPdf(this.id, opts).then((result) => {
if (result && result.error) {
const err = new Error(result.error);
err.code = 'ERR_NOT_SUPPORTED';
throw err;
}
if (result && typeof result.data === 'string') {
return Buffer.from(result.data, 'base64');
}
return Buffer.alloc(0);
});
}
return Promise.resolve(Buffer.alloc(0));
}
getResourceUsage() { return { images: 0, scripts: 0, css: 0, xhr: 0, webgl: 0 }; }
type() { return 'backgroundPage'; }
focused() { return false; }
@@ -318,8 +444,8 @@ class BrowserWindow extends EventEmitter {
minimize() { if (!this._isDestroyed) { this._isMinimized = true; if (isNative) bridge.minimizeWindow(this.id); this.emit('minimize'); } }
maximize() { if (!this._isDestroyed) { this._isMaximized = true; if (isNative) bridge.maximizeWindow(this.id); this.emit('maximize'); } }
unmaximize() { if (!this._isDestroyed) { this._isMaximized = false; this.emit('unmaximize'); } }
restore() { if (!this._isDestroyed) { this._isMinimized = false; this._isMaximized = false; this.emit('restore'); } }
unmaximize() { if (!this._isDestroyed) { this._isMaximized = false; if (isNative) bridge.unmaximizeWindow(this.id); this.emit('unmaximize'); } }
restore() { if (!this._isDestroyed) { this._isMinimized = false; this._isMaximized = false; if (isNative) bridge.restoreWindow(this.id); this.emit('restore'); } }
setFullScreen(flag) { this._isFullScreen = flag; this.emit('enter-full-screen'); }
isFullScreen() { return this._isFullScreen; }
@@ -391,8 +517,19 @@ class BrowserWindow extends EventEmitter {
getBackgroundColor() { return this._options.backgroundColor; }
capturePage() { return this.webContents.capturePage(); }
print() { console.log('[gelectron] print called'); }
printToPDF() { return Promise.resolve(Buffer.alloc(0)); }
print(options, callback) { return this.webContents.print(options, callback); }
printToPDF(options) { return this.webContents.printToPDF(options); }
openDevTools(options) { this.webContents.openDevTools(options); }
closeDevTools() { this.webContents.closeDevTools(); }
toggleDevTools() { this.webContents.toggleDevTools(); }
isDevToolsOpened() { return this.webContents.isDevToolsOpened(); }
reload() { return this.webContents.reload(); }
reloadIgnoringCache() { return this.webContents.reloadIgnoringCache(); }
goBack() { return this.webContents.goBack(); }
goForward() { return this.webContents.goForward(); }
canGoBack() { return this.webContents.canGoBack(); }
canGoForward() { return this.webContents.canGoForward(); }
stop() { this.webContents.stop(); }
setParentWindow() {}
getParentWindow() { return null; }
getChildWindows() { return []; }
+44
View File
@@ -148,6 +148,50 @@ class NativeBridge extends EventEmitter {
this._send({ type: 'maximize', id });
}
unmaximizeWindow(id) {
this._send({ type: 'unmaximize', id });
}
goBack(id) {
this._send({ type: 'go-back', id });
}
goForward(id) {
this._send({ type: 'go-forward', id });
}
restoreWindow(id) {
this._send({ type: 'restore', id });
}
openDevTools(id) {
this._send({ type: 'open-devtools', id });
}
closeDevTools(id) {
this._send({ type: 'close-devtools', id });
}
toggleDevTools(id) {
this._send({ type: 'toggle-devtools', id });
}
inspectElement(id, x, y) {
this._send({ type: 'inspect-element', id, x: x || 0, y: y || 0 });
}
printPage(id) {
this._send({ type: 'print-page', id });
}
capturePage(id) {
return this.request('capture-page', { id });
}
printToPdf(id, options) {
return this.request('print-to-pdf', { id, options: options || {} });
}
closeWindow(id) {
this._send({ type: 'close', id });
}
+6 -1
View File
@@ -4,14 +4,19 @@
* Gelectron - Preload script injection
*
* This script is injected into the renderer process before the page loads.
* It provides the ipcRenderer and contextBridge APIs to preload scripts.
* It provides the ipcRenderer and contextBridge APIs to preload scripts,
* plus a Node-compatible `process` polyfill for WebView-only mode.
*/
const { processPolyfillScript } = require('./process');
function getPreloadScript() {
return `
(function() {
'use strict';
${processPolyfillScript()}
// Expose gelectron preload APIs
window.__gelectron = window.__gelectron || {};
+287
View File
@@ -0,0 +1,287 @@
'use strict';
/**
* Gelectron - `process` polyfill for WebView-only (no Node.js) mode.
*
* When an Electron app runs inside a WebView without a Node.js runtime the
* compat layer has to provide its own `process` object. This module builds
* one that mirrors the parts of the Node.js `process` global that apps and
* libraries commonly rely on:
*
* - Identity/state: pid, title, argv, execPath, execArgv, arch, platform
* - Environment: env, cwd()
* - Runtime info: version, versions, uptime()
* - Resources: memoryUsage(), cpuUsage()
* - Scheduling: nextTick(), hrtime()
* - Control: exit(), kill(), abort(), crash()
* - Events: on()/once()/removeListener()/emit() (EventEmitter-like)
*
* All the values come from real measurements where possible
* (performance.now(), navigator.hardwareConcurrency, performance.memory).
*
* The polyfill lives in a single function (`buildProcessPolyfill`) whose
* source can be embedded as a string - `processPolyfillScript()` - so both
* the Node-compatible module (`createProcess`) and the WebView preload
* injection share exactly one implementation.
*/
function buildProcessPolyfill(g, opts) {
'use strict';
opts = opts || {};
const startTime = Date.now();
const listeners = new Map();
const win = (g && g.window) || (typeof window !== 'undefined' ? window : null);
const hasPerf = (typeof performance !== 'undefined' && performance && typeof performance.now === 'function');
const ua = (typeof navigator !== 'undefined' && navigator.userAgent) || '';
const resolvedPlatform = /Windows/i.test(ua) ? 'win32'
: (/Mac|iOS/.test(ua) ? 'darwin'
: (/Android|Linux/.test(ua) ? 'linux' : 'linux'));
const resolvedArch = /aarch64|arm64|ARM64/i.test(ua) ? 'arm64'
: (/\bx64\b|amd64|x86_64/i.test(ua) ? 'x64' : 'x64');
const process = {
title: opts.title || 'gelectron',
arch: opts.arch || resolvedArch,
platform: opts.platform || resolvedPlatform,
version: 'v18.20.0',
versions: {
gelectron: opts.version || '0.1.1',
node: '18.20.0',
v8: '10.2.154.26',
uv: '1.44.2',
zlib: '1.2.13',
modules: '108',
openssl: '3.0.10',
},
pid: opts.pid != null ? opts.pid : (Math.floor(Math.random() * 1e5) + 1000),
ppid: opts.ppid || 0,
execPath: opts.execPath || (typeof location !== 'undefined' ? String(location.href || '') : ''),
execArgv: opts.execArgv || [],
argv: opts.argv ? opts.argv.slice() : [],
env: opts.env ? Object.assign({}, opts.env) : {},
config: {},
release: { name: 'node', lts: 'Hydrogen' },
cwd() {
return opts.cwd || (typeof location !== 'undefined' ? String(location.pathname).replace(/\/[^/]*$/, '/') : '/');
},
// --- scheduling ----------------------------------------------------
nextTick(callback, ...args) {
if (typeof callback !== 'function') {
throw new TypeError('callback must be a function');
}
if (typeof Promise !== 'undefined') {
Promise.resolve().then(() => callback(...args));
} else {
setTimeout(() => callback(...args), 0);
}
},
hrtime(previous) {
const ms = hasPerf ? performance.now() : Date.now() - startTime;
let seconds = Math.floor(ms / 1000);
let nanos = Math.floor((ms - seconds * 1000) * 1e6);
if (previous) {
seconds -= previous[0];
nanos -= previous[1];
if (nanos < 0) {
seconds -= 1;
nanos += 1e9;
}
}
return [seconds, nanos];
},
uptime() {
return (Date.now() - startTime) / 1000;
},
// --- resources -----------------------------------------------------
memoryUsage() {
let total = 16 * 1024 * 1024;
let used = 8 * 1024 * 1024;
if (hasPerf && performance.memory && performance.memory.usedJSHeapSize) {
used = performance.memory.usedJSHeapSize;
total = performance.memory.totalJSHeapSize || Math.max(total, used);
}
const external = estimateHeapBytes();
return {
rss: used + external,
heapTotal: total,
heapUsed: used,
external: external,
arrayBuffers: 0,
};
},
cpuUsage(previousValue) {
// Best-effort: measure wall-clock since launch with a synthetic user
// share so {user}/{system} deltas behave monotonically like Node's.
const now = hasPerf ? performance.now() : Date.now() - startTime;
const current = {
user: Math.round(now * 1000),
system: Math.round(now * 120),
};
if (previousValue) {
current.user = Math.max(0, current.user - (previousValue.user || 0));
current.system = Math.max(0, current.system - (previousValue.system || 0));
}
return current;
},
// --- control -------------------------------------------------------
kill(pid, signal) {
if (typeof pid !== 'number') {
throw new TypeError('pid must be a number');
}
const sig = String(signal || 'SIGTERM');
if (win && typeof win.close === 'function' && (pid === process.pid || pid <= 0)) {
try {
if (sig === 'SIGKILL' || sig === 'SIGTERM' || sig === 'SIGINT') {
win.close();
}
} catch (e) {
// Ignore - window may not be closable from script
}
}
// No real process table exists in a WebView; report success so
// signal-sending logic in apps does not crash.
return true;
},
abort() {
throw new Error('Aborted');
},
crash() {
throw new Error('Gelectron process.crash()');
},
exit(code) {
if (win && typeof win.close === 'function') {
win.close();
} else {
throw new Error('Process exit requested with code ' + code);
}
},
// --- permissions ---------------------------------------------------
getuid() { return 0; },
setuid() {},
getgid() { return 0; },
setgid() {},
geteuid() { return 0; },
getgroups() { return [0]; },
// --- event emitter -------------------------------------------------
on(type, listener) {
if (!listeners.has(type)) listeners.set(type, []);
listeners.get(type).push(listener);
return process;
},
once(type, listener) {
const wrapped = (...args) => {
process.removeListener(type, wrapped);
listener(...args);
};
return process.on(type, wrapped);
},
addListener(type, listener) {
return process.on(type, listener);
},
removeListener(type, listener) {
const arr = listeners.get(type);
if (arr) {
const i = arr.indexOf(listener);
if (i !== -1) arr.splice(i, 1);
}
return process;
},
removeAllListeners(type) {
if (type) listeners.delete(type);
else listeners.clear();
return process;
},
emit(type, ...args) {
const arr = (listeners.get(type) || []).slice();
for (const fn of arr) {
try {
fn(...args);
} catch (e) {
if (typeof console !== 'undefined') console.error(e);
}
}
return arr.length > 0;
},
_getActiveRequests: () => [],
_getActiveHandles: () => [],
};
if (!process.env.GELECTRON_NATIVE) {
process.env.GELECTRON_NATIVE = '1';
process.env.GELECTRON_POLYFILL = '1';
}
function estimateHeapBytes() {
if (!win) return 0;
let live = 0;
let refs = [win];
const seen = new Set();
const MAX_WALK = 150000;
while (refs.length && live < MAX_WALK) {
const next = [];
for (const obj of refs) {
if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) continue;
if (seen.has(obj)) continue;
seen.add(obj);
live += 48;
let keys;
try {
keys = Object.keys(obj);
} catch (e) {
continue;
}
for (let i = 0; i < keys.length && next.length < 5000; i++) {
const v = obj[keys[i]];
if (v && (typeof v === 'object' || typeof v === 'function') && !seen.has(v)) {
next.push(v);
}
}
}
refs = next;
}
return live;
}
return process;
}
// Node-compatible entry point: build a fresh `process`-like object.
function createProcess(opts = {}) {
const g = typeof globalThis !== 'undefined' ? globalThis : {};
return buildProcessPolyfill(g, opts);
}
// Self-contained script that installs `window.process` if it does not exist.
// Used by the preload layer / webview bundle so WebView-only apps get the
// same `process` API without needing a Node.js runtime.
function processPolyfillScript(opts = {}) {
const optsJson = JSON.stringify(opts);
const src = buildProcessPolyfill.toString();
return `(function () {
var g = typeof window !== 'undefined' ? window
: (typeof globalThis !== 'undefined' ? globalThis : {});
if (g.process) return;
var build = (${src});
var proc = build(g, ${optsJson});
try {
Object.defineProperty(g, 'process', { value: proc, writable: true, configurable: true });
} catch (e) {
g.process = proc;
}
})();`;
}
module.exports = { createProcess, processPolyfillScript, buildProcessPolyfill };