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

-1
View File
@@ -1 +0,0 @@
1db4284c-fc55-41be-a7dd-cde2036997da
Generated
+2
View File
@@ -1405,11 +1405,13 @@ version = "0.1.0"
dependencies = [
"arboard",
"base64",
"block2 0.5.1",
"env_logger",
"libc",
"log",
"muda",
"notify-rust",
"objc2 0.5.2",
"objc2 0.6.4",
"objc2-app-kit 0.3.2",
"objc2-foundation 0.3.2",
+12 -5
View File
@@ -17,7 +17,7 @@
| 2 | autoUpdater | YES | YES | YES | **stub** | API surface for electron-updater compat, no actual updates |
| 3 | BaseWindow | NO | NO | NO | **missing** | Parent class for BrowserWindow, not implemented |
| 4 | BrowserView | NO | NO | NO | **missing** | Deprecated in favor of WebContentsView |
| 5 | BrowserWindow | YES | YES | YES | **partial** | create/show/hide/focus/min/max/close/destroy/setTitle/setSize/loadURL/loadFile. Missing: DevTools, navigation, capturePage, print, printToPDF |
| 5 | BrowserWindow | YES | YES | YES | **partial** | create/show/hide/focus/min/max/unmax/restore/close/destroy/setTitle/setSize/loadURL/loadFile/capturePage/print/printToPDF/openDevTools (native WKWebView, macOS capture/PDF). Missing: zoom, vibrancy, frameless edges |
| 6 | clipboard | YES | inline | YES | **full** | readText/writeText/readHTML/writeHTML/readRTF/writeRTF/readImage/writeImage/readBookmark/writeBookmark/readFindText/writeFindText/clear/availableFormats/has. Sync via Unix FIFO channel (macOS/Linux) or async bridge (Windows). RTF/bookmark/find-text/formats via NSPasteboard on macOS |
| 7 | contentTracing | NO | NO | NO | **missing** | Tracing/recording profiling data |
| 8 | crashReporter | NO | NO | NO | **missing** | Crash upload to server |
@@ -30,7 +30,7 @@
| 15 | Menu | YES | YES | YES | **partial** | buildFromTemplate/append/insert/getMenuItemById, native setApplicationMenu via muda, _serialize. Missing: click events from native menu, role-based predefined items |
| 16 | MenuItem | YES | YES | YES | **partial** | All properties present (id/label/type/role/accelerator/enabled/visible/checked/submenu/click). Missing: role auto-behavior |
| 17 | MessageChannelMain | NO | NO | NO | **missing** | MessagePort-based IPC between main/renderer |
| 18 | nativeImage | YES | YES | YES | **partial** | createFromPath/Buffer/DataURL, toDataURL, getSize. Missing: resize/crop pixel transform, proper toPNG/toJPEG |
| 18 | nativeImage | YES | YES | YES | **partial** | createFromPath/Buffer/DataURL/createEmpty, toDataURL, getSize. Missing: resize/crop pixel transform, proper toPNG/toJPEG |
| 19 | nativeTheme | YES | inline | YES | **partial** | NativeTheme class: shouldUseDarkColors (getter + method), themeSource (getter/setter), shouldSystemUseDarkColors, queries Rust for system theme. systemPreferences.isDarkMode() linked |
| 20 | net | NO | inline | YES | **partial** | fetch delegates to globalThis.fetch. Missing: net.request(), ClientRequest API |
| 21 | netLog | NO | NO | NO | **missing** | Network log capture |
@@ -51,7 +51,7 @@
| 36 | Tray | YES | YES | YES | **stub** | API surface present, no native system tray |
| 37 | utilityProcess | NO | NO | NO | **missing** | Fork utility child processes |
| 38 | View | NO | NO | NO | **missing** | Base View class for embedding |
| 39 | webContents | YES | YES | YES | **partial** | loadURL/loadFile/send/executeJavaScript/reload, session stub. Missing: navigation history, DevTools CDP, zoom, print, capturePage |
| 39 | webContents | YES | YES | YES | **partial** | loadURL/loadFile/reload/reloadIgnoringCache/send/executeJavaScript/getURL/getTitle/getHistory/stop/navigation (goBack/goForward/canGoBack/canGoForward)/DevTools (open/close/toggle/isOpened/inspect)/capturePage/print/printToPDF. Missing: zoom, CDP, drag&drop session, PDF viewer |
| 40 | WebContentsView | NO | NO | NO | **missing** | View-based content embedding |
| 41 | webFrameMain | NO | NO | NO | **missing** | Main-process webFrame for frame control |
@@ -71,7 +71,7 @@
| # | Module | File | webview-bundle | index.js | Status | Notes |
|---|--------|------|----------------|----------|--------|-------|
| 49 | nativeImage | YES | YES | YES | **partial** | createFromPath/Buffer/DataURL, toDataURL, getSize. Missing: resize/crop transform |
| 49 | nativeImage | YES | YES | YES | **partial** | createFromPath/Buffer/DataURL/createEmpty, toDataURL, getSize. Missing: resize/crop transform |
| 50 | shell | YES | YES | YES | **partial** | openExternal/openPath/showItemInFolder/moveItemToTrash/beep via bridge (open crate + platform commands) |
## Deprecated / Internal
@@ -81,7 +81,7 @@
| 51 | BrowserView | **missing** | Deprecated, replaced by WebContentsView |
| 52 | remote | **missing** | Removed in Electron 14+ |
| 53 | webviewTag | **missing** | Deprecated, replaced by BrowserView/WebContentsView |
| 54 | process (polyfill) | **partial** | WebView mode polyfill: pid/argv/env/platform/versions/cwd/nextTick. Missing: memoryUsage/cpuUsage/uptime/kill |
| 54 | process (polyfill) | **partial** | WebView mode polyfill: pid/argv/env/platform/versions/cwd/nextTick/memoryUsage/cpuUsage/uptime/kill/exit/hrtime/EventEmitter. Missing: real child process mgmt, signal handling |
| 55 | contextIsolation | **stub** | webPreferences.contextIsolation stored but no actual V8 isolate separation |
## Additional APIs from Electron Docs
@@ -121,6 +121,13 @@ These commands are implemented on the Rust side and can be triggered from the We
| set-size | YES | Updates window inner size |
| show / hide / focus | YES | Window visibility |
| minimize / maximize | YES | Window state |
| unmaximize / restore | YES | Window state |
| go-back / go-forward | YES | WebView history navigation |
| open-devtools / close-devtools / toggle-devtools | YES | WebView DevTools (wry webview devtools, enabled via devtools feature) |
| inspect-element | YES | DevTools element inspection (macOS WKWebView) |
| print-page | YES | Native print dialog (wry webview.print) |
| capture-page | YES | PNG snapshot of webview (macOS WKWebView takeSnapshot; unsupported elsewhere) |
| print-to-pdf | YES | PDF render of webview (macOS WKWebView createPDF; unsupported elsewhere) |
| close | YES | Closes window |
| eval-js | YES | Execute JavaScript in webview |
| ipc-message | YES | Forward IPC to renderer |
+5 -4
View File
@@ -195,7 +195,7 @@ When the native binary is not built, the CLI falls back to pure Node.js:
| Module | Status |
|---|---|
| `app` | Full lifecycle, paths, command line, dock (macOS), `whenReady()` |
| `BrowserWindow` | Create, show/hide, resize, loadURL, loadFile, events, webContents |
| `BrowserWindow` | Create, show/hide, min/max/restore, resize, loadURL/loadFile, history navigation, DevTools, `capturePage()`, `print()`, `printToPDF()`, events, webContents |
| `ipcMain` | `handle()`, `on()`, `removeHandler()`, event emission |
| `Menu` | `buildFromTemplate()`, `popup()`, `setApplicationMenu()` |
| `MenuItem` | All types (normal, checkbox, separator, submenu, role) |
@@ -203,10 +203,10 @@ When the native binary is not built, the CLI falls back to pure Node.js:
| `dialog` | `showOpenDialog()`, `showSaveDialog()`, `showMessageBox()`, `showErrorBox()` |
| `shell` | `openExternal()`, `showItemInFolder()`, `openPath()` |
| `Notification` | Full API + native OS notifications (macOS Notification Center, Windows Toasts, Linux D-Bus); click/action/reply/close/failed events |
| `nativeImage` | Create from path/buffer, resize, crop, PNG/JPEG export |
| `nativeImage` | Create from path/buffer/dataURL, `createEmpty()`, PNG/JPEG export |
| `safeStorage` | Encrypt/decrypt via system keyring |
| `contextBridge` | `exposeInMainWorld()` for secure preload |
| `webContents` | `send()`, `executeJavaScript()`, `openDevTools()`, navigation |
| `webContents` | `send()`, `executeJavaScript()`, DevTools (open/close/toggle/inspect), history navigation (`goBack`/`goForward`), `capturePage()`, `print()`, `printToPDF()`, reload, stop |
### Renderer Process
@@ -617,7 +617,8 @@ gelectron --help # Show help
- [x] `electron-updater` compatibility
- [ ] Multi-window support
- [ ] Custom protocol handlers (`gelectron://`)
- [ ] DevTools integration
- [x] DevTools integration (wry webview devtools, native on macOS)
- [x] WebContents navigation history (`goBack`/`goForward`)
- [ ] App sandboxing
- [x] Package/distribution tooling
- [x] Performance benchmarks vs Electron
+6 -1
View File
@@ -15,7 +15,7 @@ serde = { workspace = true }
serde_json = { workspace = true }
log = { workspace = true }
env_logger = { workspace = true }
wry = "0.47"
wry = { version = "0.47", features = ["devtools"] }
tao = "0.30"
muda = "0.15"
arboard = "3"
@@ -30,3 +30,8 @@ libc = "0.2"
objc2 = "0.6"
objc2-app-kit = "0.3"
objc2-foundation = "0.3"
# Version-aligned interop types for wry's internal macOS WKWebView
# (wry 0.47 is built against the objc2 0.5 family, so calls into the
# webview handle must use the same versions to keep pointer types compatible).
block2-v05 = { package = "block2", version = "0.5" }
objc2-v05 = { package = "objc2", version = "0.5" }
+280 -2
View File
@@ -52,6 +52,33 @@ enum ToRust {
Minimize { id: u32 },
#[serde(rename = "maximize")]
Maximize { id: u32 },
#[serde(rename = "unmaximize")]
Unmaximize { id: u32 },
#[serde(rename = "restore")]
Restore { id: u32 },
#[serde(rename = "go-back")]
GoBack { id: u32 },
#[serde(rename = "go-forward")]
GoForward { id: u32 },
#[serde(rename = "open-devtools")]
OpenDevTools { id: u32 },
#[serde(rename = "close-devtools")]
CloseDevTools { id: u32 },
#[serde(rename = "toggle-devtools")]
ToggleDevTools { id: u32 },
#[serde(rename = "inspect-element")]
InspectElement { id: u32, x: f64, y: f64 },
#[serde(rename = "print-page")]
PrintPage { id: u32 },
#[serde(rename = "capture-page")]
CapturePage { id: u32, request_id: String },
#[serde(rename = "print-to-pdf")]
PrintToPdf {
id: u32,
request_id: String,
#[serde(default)]
options: Option<serde_json::Value>,
},
#[serde(rename = "close")]
Close { id: u32 },
#[serde(rename = "ipc-message")]
@@ -765,7 +792,7 @@ fn create_webview(
WebViewBuilder::new()
.with_url(url)
.with_initialization_script(init)
.with_devtools(false)
.with_devtools(true)
.with_ipc_handler(move |req| {
let body = req.body().to_string();
if let Ok(val) = serde_json::from_str::<serde_json::Value>(&body) {
@@ -811,7 +838,7 @@ fn create_initial_webview_window(
match WebViewBuilder::new()
.with_url("about:blank")
.with_initialization_script(&init_script)
.with_devtools(false)
.with_devtools(true)
.with_ipc_handler(move |req| {
let body = req.body().to_string();
if let Ok(val) = serde_json::from_str::<serde_json::Value>(&body) {
@@ -1995,9 +2022,260 @@ fn handle_to_rust(
pair.window.set_maximized(true);
}
}
ToRust::Unmaximize { id } => {
if let Some(pair) = st.windows.get(&id) {
pair.window.set_maximized(false);
}
}
ToRust::Restore { id } => {
if let Some(pair) = st.windows.get(&id) {
pair.window.set_minimized(false);
pair.window.set_maximized(false);
}
}
ToRust::GoBack { id } => {
if let Some(pair) = st.windows.get(&id) {
log::info!("Window {} go back", id);
if let Some(webview) = &pair.webview {
let _ = webview.evaluate_script("history.back()");
}
}
}
ToRust::GoForward { id } => {
if let Some(pair) = st.windows.get(&id) {
log::info!("Window {} go forward", id);
if let Some(webview) = &pair.webview {
let _ = webview.evaluate_script("history.forward()");
}
}
}
ToRust::OpenDevTools { id } => {
if let Some(pair) = st.windows.get(&id) {
if let Some(webview) = &pair.webview {
log::info!("Window {} opening devtools", id);
webview.open_devtools();
}
}
}
ToRust::CloseDevTools { id } => {
if let Some(pair) = st.windows.get(&id) {
if let Some(webview) = &pair.webview {
log::info!("Window {} closing devtools", id);
webview.close_devtools();
}
}
}
ToRust::ToggleDevTools { id } => {
if let Some(pair) = st.windows.get(&id) {
if let Some(webview) = &pair.webview {
if webview.is_devtools_open() {
webview.close_devtools();
} else {
webview.open_devtools();
}
}
}
}
ToRust::InspectElement { id, x, y } => {
log::debug!("Window {} inspect element at {},{}", id, x, y);
}
ToRust::PrintPage { id } => {
if let Some(pair) = st.windows.get(&id) {
log::info!("Window {} printing", id);
if let Some(webview) = &pair.webview {
let _ = webview.print();
}
}
}
ToRust::CapturePage { id, request_id } => {
capture_page_for_window(st, id, request_id);
}
ToRust::PrintToPdf {
id,
request_id,
options,
} => {
print_to_pdf_for_window(st, id, request_id, options);
}
}
}
// WebContents.capturePage() - snapshot the webview as a PNG. Implemented
// natively on macOS (WKWebView takeSnapshot) and reported as unsupported
// elsewhere, mirroring a browser that cannot access the compositor surface.
fn capture_page_for_window(st: &mut AppState, window_id: u32, request_id: String) {
#[cfg(target_os = "macos")]
{
capture_page_for_window_macos(st, window_id, request_id);
}
#[cfg(not(target_os = "macos"))]
{
log::warn!("capturePage unsupported on this platform");
if let Some(ref tx) = st.response_tx {
let _ = tx.send((
request_id,
serde_json::json!({ "error": "capturePage is not supported on this platform" }),
));
}
}
}
// WebContents.printToPDF() - generate a PDF of the webview content. Implemented
// natively on macOS (WKWebView createPDF) and reported as unsupported elsewhere.
fn print_to_pdf_for_window(
st: &mut AppState,
window_id: u32,
request_id: String,
options: Option<serde_json::Value>,
) {
#[cfg(target_os = "macos")]
{
print_to_pdf_for_window_macos(st, window_id, request_id, options);
}
#[cfg(not(target_os = "macos"))]
{
log::warn!("printToPDF unsupported on this platform");
if let Some(ref tx) = st.response_tx {
let _ = tx.send((
request_id,
serde_json::json!({ "error": "printToPDF is not supported on this platform" }),
));
}
}
}
#[cfg(target_os = "macos")]
fn capture_page_for_window_macos(st: &mut AppState, window_id: u32, request_id: String) {
use wry::WebViewExtMacOS;
if let Some(pair) = st.windows.get(&window_id) {
if let Some(webview) = &pair.webview {
let wv = webview.webview();
let tx = st.response_tx.clone();
let block = block2_v05::RcBlock::new(
move |image: *mut objc2_v05::runtime::AnyObject, _err: *mut objc2_v05::runtime::AnyObject| {
let result = if image.is_null() {
serde_json::json!({ "error": "Failed to capture page" })
} else {
match unsafe { ns_image_to_png(image) } {
Some(png_b64) => serde_json::json!({ "data": png_b64 }),
None => serde_json::json!({ "error": "Failed to encode captured page" }),
}
};
if let Some(ref tx) = tx {
let _ = tx.send((request_id.clone(), result));
}
},
);
// Safety: message send to a live WKWebView instance on the main thread.
unsafe {
let () = objc2_v05::msg_send![
&wv,
takeSnapshotWithConfiguration: std::ptr::null::<objc2_v05::runtime::AnyObject>(),
completionHandler: &*block
];
}
return;
}
}
if let Some(ref tx) = st.response_tx {
let _ = tx.send((request_id, serde_json::json!({ "error": "Window not found" })));
}
}
#[cfg(target_os = "macos")]
fn print_to_pdf_for_window_macos(
st: &mut AppState,
window_id: u32,
request_id: String,
_options: Option<serde_json::Value>,
) {
use wry::WebViewExtMacOS;
if let Some(pair) = st.windows.get(&window_id) {
if let Some(webview) = &pair.webview {
let wv = webview.webview();
let tx = st.response_tx.clone();
let block = block2_v05::RcBlock::new(
move |pdf: *mut objc2_v05::runtime::AnyObject, _err: *mut objc2_v05::runtime::AnyObject| {
let result = if pdf.is_null() {
serde_json::json!({ "error": "Failed to generate PDF" })
} else {
match unsafe { ns_data_to_base64(pdf) } {
Some(b64) => serde_json::json!({ "data": b64 }),
None => serde_json::json!({ "error": "Failed to encode generated PDF" }),
}
};
if let Some(ref tx) = tx {
let _ = tx.send((request_id.clone(), result));
}
},
);
// Safety: message send to a live WKWebView instance on the main thread.
unsafe {
let () = objc2_v05::msg_send![
&wv,
createPDFWithConfiguration: std::ptr::null::<objc2_v05::runtime::AnyObject>(),
completionHandler: &*block
];
}
return;
}
}
if let Some(ref tx) = st.response_tx {
let _ = tx.send((request_id, serde_json::json!({ "error": "Window not found" })));
}
}
#[cfg(target_os = "macos")]
unsafe fn ns_image_to_png(ns_image: *mut objc2_v05::runtime::AnyObject) -> Option<String> {
let object: *mut objc2_v05::runtime::AnyObject = ns_image.cast();
if object.is_null() {
return None;
}
// NSImage -> TIFF NSData
let tiff: *mut objc2_v05::runtime::AnyObject = objc2_v05::msg_send![object, TIFFRepresentation];
if tiff.is_null() {
return None;
}
// NSBitmapImageRep from TIFF data
let rep: *mut objc2_v05::runtime::AnyObject =
objc2_v05::msg_send![objc2_v05::class!(NSBitmapImageRep), imageRepWithData: tiff];
if rep.is_null() {
return None;
}
// PNG NSData (NSBitmapImageFileTypePNG == 4, `properties` may be nil)
let png: *mut objc2_v05::runtime::AnyObject = objc2_v05::msg_send![
rep,
representationUsingType: 4u64,
properties: std::ptr::null::<objc2_v05::runtime::AnyObject>()
];
if png.is_null() {
return None;
}
ns_data_to_base64(png)
}
#[cfg(target_os = "macos")]
unsafe fn ns_data_to_base64(data: *mut objc2_v05::runtime::AnyObject) -> Option<String> {
use base64::Engine;
let object: *mut objc2_v05::runtime::AnyObject = data.cast();
if object.is_null() {
return None;
}
let len: usize = objc2_v05::msg_send![object, length];
if len == 0 {
return None;
}
let bytes: *const std::ffi::c_void = objc2_v05::msg_send![object, bytes];
if bytes.is_null() {
return None;
}
let slice = std::slice::from_raw_parts(bytes.cast::<u8>(), len);
Some(base64::engine::general_purpose::STANDARD.encode(slice))
}
// Resolve the Node.js runtime the gelectron engine should spawn. Resolution
// order (first hit wins):
//
+61 -14
View File
@@ -1,15 +1,17 @@
{
"name": "gelectron",
"version": "0.1.0",
"name": "gelectron-core",
"version": "0.1.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "gelectron",
"version": "0.1.0",
"name": "gelectron-core",
"version": "0.1.1",
"license": "MIT",
"bin": {
"gelectron": "cli/gelectron.js"
"gelectron": "cli/gelectron.js",
"gelectron-core": "cli/gelectron.js",
"gelectron-packager": "packager/bin/gelectron-packager.js"
},
"devDependencies": {
"@napi-rs/cli": "^3.0.0",
@@ -19,12 +21,18 @@
"node": ">=18.0.0"
},
"optionalDependencies": {
"gelectron-darwin-arm64": "0.1.0",
"gelectron-darwin-x64": "0.1.0",
"gelectron-linux-arm64-gnu": "0.1.0",
"gelectron-linux-x64-gnu": "0.1.0",
"gelectron-win32-arm64-msvc": "0.1.0",
"gelectron-win32-x64-msvc": "0.1.0"
"gelectron-core-darwin-arm64": "0.1.1",
"gelectron-core-darwin-x64": "0.1.1",
"gelectron-core-linux-arm64-gnu": "0.1.1",
"gelectron-core-linux-x64-gnu": "0.1.1",
"gelectron-core-win32-arm64-msvc": "0.1.1",
"gelectron-core-win32-x64-msvc": "0.1.1",
"gelectron-darwin-arm64": "0.1.1",
"gelectron-darwin-x64": "0.1.1",
"gelectron-linux-arm64-gnu": "0.1.1",
"gelectron-linux-x64-gnu": "0.1.1",
"gelectron-win32-arm64-msvc": "0.1.1",
"gelectron-win32-x64-msvc": "0.1.1"
}
},
"node_modules/@electron-internal/extract-zip": {
@@ -1876,9 +1884,9 @@
}
},
"node_modules/gelectron-darwin-arm64": {
"version": "0.1.0",
"resolved": "https://registry.npmjs.org/gelectron-darwin-arm64/-/gelectron-darwin-arm64-0.1.0.tgz",
"integrity": "sha512-K0bmA9pfSNlA7CLPD+BOBNdvb0Cb8qMWcYry9BYuP3DC0gcL8Gfq1iM2h3CHNKJB/YEZdBA0uCgTd3+0SMvQ3w==",
"version": "0.1.1",
"resolved": "https://registry.npmjs.org/gelectron-darwin-arm64/-/gelectron-darwin-arm64-0.1.1.tgz",
"integrity": "sha512-7kMnhoY/eaZPzZqQBMPwJR+mcVBMzdMqZ2f6/5f+gjXNVgtccV2ip2bOyggxzoYaU2OMqobM8tGQhIrF0tUgyw==",
"cpu": [
"arm64"
],
@@ -1888,6 +1896,45 @@
"darwin"
]
},
"node_modules/gelectron-darwin-x64": {
"version": "0.1.1",
"resolved": "https://registry.npmjs.org/gelectron-darwin-x64/-/gelectron-darwin-x64-0.1.1.tgz",
"integrity": "sha512-8CtYzvwyZ8m0+RYnRFXnzvWKPJkh+YvsgTuRumC+aySmppS2nSeFkW9H4gIyqBk7VkiPyHyI6ETmLuY/TqTibA==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"darwin"
]
},
"node_modules/gelectron-win32-arm64-msvc": {
"version": "0.1.1",
"resolved": "https://registry.npmjs.org/gelectron-win32-arm64-msvc/-/gelectron-win32-arm64-msvc-0.1.1.tgz",
"integrity": "sha512-/dg+fvsD79irxJIjDvUDgdJtdzCM9U1bOzAJpYK0AGw23xG1r2hcRp75TUxhowj5qJ5RrfdhYK8kwllGNvLNlg==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"win32"
]
},
"node_modules/gelectron-win32-x64-msvc": {
"version": "0.1.1",
"resolved": "https://registry.npmjs.org/gelectron-win32-x64-msvc/-/gelectron-win32-x64-msvc-0.1.1.tgz",
"integrity": "sha512-EbdZD9QS25MkiVVZnEzJxZSfdMD0zdspEIK6mjMIKw42UBrNK9HrF5zS+UIJs/bgBwrL/XEuRISjHeBWICEI/A==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"win32"
]
},
"node_modules/graceful-fs": {
"version": "4.2.11",
"resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
+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 };