Repository navigation
Conversation
|
Warning Review limit reached
Next review available in: 2 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (11)
📝 WalkthroughWalkthroughThe change adds an optional 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 6176e7ea-dee8-4cae-8e73-3a67275a301f
📒 Files selected for processing (16)
src/main/browser/browser-manager.test.tssrc/main/browser/browser-manager.tssrc/main/browser/browser-window-close-guard.test.tssrc/main/browser/browser-window-close-guard.tssrc/main/window/createMainWindow.test.tssrc/main/window/createMainWindow.tssrc/renderer/src/components/browser-pane/BrowserPane.tsxsrc/renderer/src/components/browser-pane/BrowserPane.webview-preferences.test.tssrc/renderer/src/components/browser-pane/browser-page-webview.tssrc/renderer/src/hooks/useIpcEvents.test.tssrc/renderer/src/hooks/useIpcEvents.tssrc/renderer/src/store/slices/browser.tssrc/shared/browser-window-close-policy.tssrc/shared/types.tssrc/shared/workspace-session-schema.tstests/e2e/browser-tab.spec.ts
| const shouldGuardWindowClose = | ||
| inheritedOwnerContext === null && | ||
| guest.getType() === 'webview' && | ||
| options.allowWindowClose !== true | ||
| const disposeAntiDetection = this.injectAntiDetection( | ||
| guest, | ||
| shouldGuardWindowClose ? BROWSER_WINDOW_CLOSE_GUARD_SCRIPT : '' | ||
| ) | ||
| const installWindowCloseGuard = (): void => { | ||
| if (!shouldGuardWindowClose || guest.isDestroyed()) { | ||
| return | ||
| } | ||
| try { | ||
| void guest.executeJavaScript(BROWSER_WINDOW_CLOSE_GUARD_SCRIPT).catch(() => {}) | ||
| } catch { | ||
| // Guest may detach between dom-ready and script evaluation. | ||
| } | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🌐 Web query:
Electron 43 WebContents debugger Page.addScriptToEvaluateOnNewDocument behavior when registration occurs after a navigation has started
💡 Result:
In Electron (including version 43), the Chrome DevTools Protocol (CDP) method Page.addScriptToEvaluateOnNewDocument is designed to evaluate a script in every frame upon creation, specifically before any of the frame's other scripts are loaded [1][2][3]. Regarding behavior when registration occurs after a navigation has started: 1. Standard Behavior: Page.addScriptToEvaluateOnNewDocument registers a script that persists across navigations for the lifetime of the DevTools session (or until removed via Page.removeScriptToEvaluateOnNewDocument) [4]. When you register this script after a navigation has already initiated (e.g., after the browser has begun loading a new URL), the script will typically not apply to the current, ongoing navigation if the frame creation event has already passed [1][2][3]. It will, however, apply to subsequent navigations or new frames created after the registration is successfully processed [1][2][3]. 2. The runImmediately Parameter: The CDP documentation includes an optional runImmediately parameter [3][5]. If runImmediately is set to true, the script will run immediately on existing execution contexts or worlds [2][3]. If you need the script to execute even if registered mid-navigation, enabling this parameter (if available in your specific environment's protocol version) may allow the script to take effect on the current document [3]. 3. Electron-Specific Context: Electron's webContents.debugger attaches to the WebContents and manages CDP sessions [6]. If you are experiencing issues with scripts not being applied, ensure that Page.enable has been called on the debugger session; without it, many Page domain events and commands may not function as expected [7]. Additionally, be aware that Electron internally manages RenderFrameHost lifecycle, and in recent versions (including those around 43), internal re-attachments of the debugger session during navigation can occasionally lead to dropped messages or protocol state resets if not handled carefully [8][9]. To ensure consistent behavior, it is best practice to: - Call Page.enable immediately after attaching the debugger [7]. - Register your Page.addScriptToEvaluateOnNewDocument scripts as early as possible, ideally before initiating any navigation (e.g., before calling webContents.loadURL). - If you must register dynamically, consider using the runImmediately: true flag if the protocol version supports it [3].
Citations:
- 1: https://bugzilla.mozilla.org/show_bug.cgi?id=1597879
- 2: https://github.com/chromedp/cdproto/blob/master/page/page.go
- 3: https://chromedevtools.github.io/devtools-protocol/tot/Page/
- 4: De-register function when a page is navigated puppeteer/puppeteer#5677
- 5: https://chromedevtools.github.io/devtools-protocol/1-3/Page/
- 6: https://electronjs.org/docs/latest/api/debugger
- 7: How to use Page.addScriptToEvaluateOnNewDocument in CDPSession? puppeteer/puppeteer#10094
- 8: Page.frameAttached Chrome Devtools Protocol events are not being dispatched electron/electron#46048
- 9: fix: devTools network events dropped on RenderFrameHost swap electron/electron#51959
🏁 Script executed:
#!/usr/bin/env bash
set -euo pipefail
echo "Repository files matching browser-manager:"
fd -a 'browser-manager\.ts$' . || true
file="$(fd 'browser-manager\.ts$' . | head -n 1 || true)"
if [ -n "$file" ]; then
echo "---- outline ----"
ast-grep outline "$file" --match injectAntiDetection --view expanded || true
ast-grep outline "$file" --match attachGuestPolicies --view expanded || true
echo "---- relevant sections ----"
sed -n '1,120p' "$file" | cat -n
sed -n '260,320p' "$file" | cat -n
sed -n '620,710p' "$file" | cat -n
echo "---- definitions ----"
rg -n "BROWSER_WINDOW_CLOSE_GUARD_SCRIPT|injectAntiDetection|attachGuestPolicies|addScriptToEvaluateOnNewDocument|debugger|dom-ready|window\.close" "$file"
fi
echo "---- package electron version ----"
if [ -f package.json ]; then jq -r '.dependencies.electron, .devDependencies.electron' package.json 2>/dev/null || true; fi
if [ -f package-lock.json ]; then rg -n '"electron"' package-lock.json | head -n 20 || true; fiRepository: stablyai/orca
Length of output: 14512
🌐 Web query:
Electron debugger WebContents debugger Page.addScriptToEvaluateOnNewDocument runImmediately API availability
💡 Result:
The Page.addScriptToEvaluateOnNewDocument method is a part of the Chrome DevTools Protocol (CDP), not a native method of the Electron WebContents API [1][2]. In Electron, you access this functionality by using the webContents.debugger API, which allows you to send raw CDP commands [2][3]. Regarding the runImmediately parameter: 1. Availability: The runImmediately boolean parameter is defined in the Chrome DevTools Protocol specification for the Page.addScriptToEvaluateOnNewDocument method [1]. It is officially marked as experimental in the protocol documentation [1]. 2. Functionality: When set to true, this parameter causes the script to run immediately on existing execution contexts or worlds, rather than waiting for new navigations [1][4]. The default value is false [1][4]. 3. Electron Context: Because Electron's webContents.debugger.sendCommand method is a generic transport for CDP commands, it supports any command defined in the protocol version used by the underlying Chromium engine [2][3]. Therefore, if the version of Chromium bundled with your specific Electron release includes support for this experimental Page.addScriptToEvaluateOnNewDocument parameter in its CDP implementation, you can use it by passing it in the commandParams object [1][2]. To use it in Electron, you would typically structure your code as follows: const { BrowserWindow } = require('electron'); const win = new BrowserWindow; // Attach the debugger win.webContents.debugger.attach('1.3'); // Ensure a compatible protocol version // Send the command with the experimental parameter win.webContents.debugger.sendCommand('Page.addScriptToEvaluateOnNewDocument', { source: 'console.log("Hello from debugger");', runImmediately: true // Experimental parameter }).then((params) => { console.log('Script added with ID:', params.identifier); }).catch((err) => { console.error('Failed to add script:', err); }); Because runImmediately is considered experimental, it may be subject to changes or removal in future Chromium updates, and its availability depends entirely on the specific version of Chromium embedded in your Electron version [1].
Citations:
- 1: https://chromedevtools.github.io/devtools-protocol/tot/Page/
- 2: https://electronjs.org/docs/latest/api/debugger
- 3: https://github.com/electron/electron/blob/main/docs/api/debugger.md
- 4: https://cefsharp.github.io/api/118.6.x/html/M_CefSharp_DevTools_Page_PageClient_AddScriptToEvaluateOnNewDocumentAsync.htm
🏁 Script executed:
#!/usr/bin/env bash
set -euo pipefail
file="src/main/browser/browser-manager.ts"
echo "---- attachGuestPolicies call sites and surrounding code ----"
sed -n '620,760p' "$file" | cat -n
echo "---- attachGuestPolicies cleanup and later calls ----"
sed -n '880,1150p' "$file" | cat -n
echo "---- AntiDetection script and Guard script contents ----"
fd -a 'anti-detection\.ts$|anti-detection\.js$' . | while read -r f; do echo "---- $f ----"; wc -l "$f"; sed -n '1,220p' "$f" | cat -n; done
fd -a 'browser-window-close-guard\.ts$|browser-window-close-guard\.js$' . | while read -r f; do echo "---- $f ----"; wc -l "$f"; sed -n '1,220p' "$f" | cat -n; done
echo "---- guest creation/registration references ----"
rg -n "attachGuestPolicies\\(|shouldGuardWindowClose|load\\(|loadURL|navigate|dom-ready|addCommandMessageHandler|executeJavaScriptInIsolatedWorld" "$file" | sed -n '1,220p'Repository: stablyai/orca
Length of output: 28870
🌐 Web query:
Electron 43 WebContents WebContentsDebugger sendCommand Page.addScriptToEvaluateOnNewDocument debugger attached before navigation
💡 Result:
In Electron, using the Chrome DevTools Protocol (CDP) to call Page.addScriptToEvaluateOnNewDocument allows you to inject JavaScript into every frame upon creation, guaranteeing that it executes before any of the frame's own scripts load [1][2]. To use this successfully, especially in scenarios involving navigation or frame creation, follow these critical technical practices: 1. Enable the Page Domain: You must call Page.enable before invoking Page.addScriptToEvaluateOnNewDocument [2][3]. If you do not explicitly enable the domain, the command may fail or have no effect [3]. 2. Handling Navigation and Race Conditions: - Persistence: Page.addScriptToEvaluateOnNewDocument persists across navigations and page reloads [4]. You generally only need to register the script once per debugging session [2]. - Timing Issues: While the protocol guarantees the script runs "upon creation (before loading frame's scripts)," relying on this for critical initialization can still lead to race conditions if other commands (like Runtime.evaluate or navigation triggers) occur simultaneously [5][6]. - Synchronization: If you are attaching to new targets (such as iframes or popups) that may pause at startup (e.g., using Target.setAutoAttach with waitForDebuggerOnStart), you must ensure your initialization commands—including Page.enable and Page.addScriptToEvaluateOnNewDocument—are sent and acknowledged before you issue the Runtime.runIfWaitingForDebugger command to resume the target [6]. 3. Implementation Example: javascript const dbg = win.webContents.debugger; dbg.attach("1.3"); // Enable domains before sending other commands await dbg.sendCommand("Page.enable"); await dbg.sendCommand("Runtime.enable"); // Register the script await dbg.sendCommand("Page.addScriptToEvaluateOnNewDocument", { source: `console.log('Injected before navigation/frame load');` }); // Now safe to navigate win.webContents.loadURL("https://example.com"); If you encounter issues where the script does not seem to run, verify that you have attached to the correct target (especially if dealing with out-of-process iframes) and that the Page domain is enabled specifically for that session ID [2][3].
Citations:
- 1: https://chromedevtools.github.io/devtools-protocol/tot/Page/
- 2: https://nullpt.rs/reverse-engineering-browser
- 3: How to use Page.addScriptToEvaluateOnNewDocument in CDPSession? puppeteer/puppeteer#10094
- 4: Install the Cypress bridge via
Page.addScriptToEvaluateOnNewDocumentcypress-io/cypress#33849 - 5: Runtime.evaluate can happen before Page.addScriptToEvaluateOnNewDocument ChromeDevTools/devtools-protocol#182
- 6: Solve init script race with Debugger.resume at frame init script injection time browserbase/stagehand#1719
🌐 Web query:
Electron 43 webContents debugger on navigate detach Page.addScriptToEvaluateOnNewDocument
💡 Result:
In Electron, the webContents debugger's attach/detach behavior and the usage of Page.addScriptToEvaluateOnNewDocument are governed by Chromium's DevTools Protocol and Electron's internal debugger implementation [1][2]. 1. Debugger Detach on Navigation: By design, the Electron webContents.debugger does not automatically detach simply because a navigation occurred [2]. Electron's debugger implementation (see shell/browser/api/electron_api_debugger.cc) is designed to maintain the debugging session across primary main-frame navigations by following the RenderFrameHost swaps [2]. Explicit detachment only occurs when debugger.detach() is called, the webContents is destroyed, or DevTools is opened for the same webContents (which forces the previous debugger instance to detach) [1][3]. 2. Page.addScriptToEvaluateOnNewDocument: This command registers a script to be injected into every new document created within the target frame [4]. When using this via the webContents.debugger, the script registration persists as long as the debugging session (the CDPSession) remains active [4]. If the debugger is detached, any registered scripts are cleared by the browser because the session that owned them has been terminated [5]. 3. Practical Considerations: If you experience a "Session closed" or "Target detached" error after navigation, it often implies the debugging session was interrupted or lost [5]. While standard navigation does not trigger a detach, certain lifecycle events—or errors in handling RenderFrameHost changes—could theoretically interrupt the session [2][6]. Ensure that Page.enable is called before sending other commands, as missing domain enablement is a common cause for protocol-related failures [7]. If you need scripts to persist regardless of debugger state, consider Electron's webContents.preload scripts or the did-create-window / did-frame-finish-load events instead.
Citations:
- 1: https://github.com/electron/electron/blob/main/docs/api/debugger.md
- 2: https://github.com/electron/electron/blob/master/shell/browser/api/electron_api_debugger.cc
- 3: https://electronjs.org/docs/latest/api/debugger
- 4: https://bugzilla.mozilla.org/show_bug.cgi?id=1597879
- 5: Protocol error (Page.addScriptToEvaluateOnNewDocument): Session closed Overmiind/Puppeteer-sharp-extra#21
- 6: fix: devTools network events dropped on RenderFrameHost swap electron/electron#51959
- 7: How to use Page.addScriptToEvaluateOnNewDocument in CDPSession? puppeteer/puppeteer#10094
🌐 Web query:
Chromium WebContents navigation attach debugger Page.addScriptToEvaluateOnNewDocument initial script drops CDP command before first commit
💡 Result:
The Chromium Page.addScriptToEvaluateOnNewDocument command is designed to inject scripts into every frame upon creation, specifically before the frame's own scripts load [1]. When issues arise—such as scripts failing to execute, being dropped, or racing against other commands during early navigation stages—they typically stem from the timing of execution context creation [2][3]. Key Technical Context: 1. Context Timing and Races: Because Page.addScriptToEvaluateOnNewDocument registers a "preload" script, it relies on the browser creating a new execution context to trigger the evaluation [2][3]. If a navigation commit occurs or a frame is created and another command (like Runtime.evaluate) is issued simultaneously, the script may not have been evaluated yet, leading to race conditions where subsequent commands execute before the preload script [4]. 2. Frame/Navigation Edge Cases: Historically, Chromium had issues where certain navigation events (e.g., iframe creation or cancellations via document.open) failed to trigger the required isolated world or execution context creation [2][3]. This prevented the preload script from being evaluated [2][3]. Patches have been implemented to ensure these worlds are created whenever the main execution context is established [2]. 3. Debugger Attachment and "First Commit": If you are attaching a debugger, the browser may be in an initial empty document state. There is a distinction between the "initial" state and the "real" document state. Chromium developers have noted that forcing context evaluation in initial empty documents can sometimes conflict with other components (like GuestView), which historically caused some commands to be skipped or fail in those early stages [3][5]. 4. Mitigation/Workarounds: - Ensure the debugger has fully enabled the necessary domains (e.g., Runtime.enable, Page.enable) before initiating navigation [6]. - If you need to ensure a script runs in contexts that might already exist or are being created during a transition, you can use the runImmediately parameter (if supported by your target version) to attempt evaluation in existing contexts [7]. - If you encounter hangs or drops, ensure your automation framework properly awaits navigation events (e.g., waiting for the load event or specific navigation lifecycle milestones) before attempting to interact with the page via Runtime commands, as this guarantees the Page.addScriptToEvaluateOnNewDocument script has had the opportunity to run [4][6]. If you are experiencing specific command drops, it is recommended to verify if you are hitting an edge case related to iframe lifecycle or if your automation is simply racing the browser's context initialization [4][5]. Checking if the issue persists when using runImmediately for existing contexts is a common troubleshooting step [7].
Citations:
- 1: https://chromedevtools.github.io/devtools-protocol/tot/Page/
- 2: chromium/chromium@6f320e2
- 3: chromium/chromium@f9fe901
- 4: Runtime.evaluate can happen before Page.addScriptToEvaluateOnNewDocument ChromeDevTools/devtools-protocol#182
- 5: https://groups.google.com/a/chromium.org/g/devtools-reviews/c/YBwE4_ZFZCA
- 6: staktrace/gecko-dev@cb6f994
- 7: chromium/chromium@267dbb8
🌐 Web query:
Electron 43 webContents debugger sendCommand returns Promise if debugger not attached Page.addScriptToEvaluateOnNewDocument
💡 Result:
In Electron 43, the webContents.debugger.sendCommand method always returns a Promise that resolves with the command's response or rejects if the command fails [1][2]. If the debugger is not attached, the call will fail and the returned Promise will be rejected with an error (e.g., "No target available" or a similar error indicating the debugger is not active) [3]. The sendCommand method requires that the debugger be successfully attached to the target via webContents.debugger.attach() before any commands are executed [1][4]. Regarding Page.addScriptToEvaluateOnNewDocument: This is a method of the Chrome DevTools Protocol (CDP), not a direct method on the Electron debugger object [1][5]. To use it, you must send it as a command via webContents.debugger.sendCommand('Page.addScriptToEvaluateOnNewDocument', params) [1][3]. Important considerations when using Page.addScriptToEvaluateOnNewDocument in Electron: 1. Prerequisite: You must first enable the Page domain by calling Page.enable before you can successfully use Page.addScriptToEvaluateOnNewDocument [6]. 2. Functionality: This command instructs the browser to evaluate the provided script in every frame upon creation, before any other scripts are loaded [5]. 3. Limitations: If the debugger is not attached, the sendCommand call will fail as described above [3]. Additionally, note that this CDP method may not consistently apply to iframes created via certain dynamic methods (like srcdoc or document.open) depending on the underlying Chromium version's behavior [7][8]. Top results: [1][3][5][6]
Citations:
- 1: https://electronjs.org/docs/latest/api/debugger
- 2: https://github.com/electron/electron/blob/main/docs/api/debugger.md
- 3: https://github.com/electron/electron/blob/master/shell/browser/api/electron_api_debugger.cc
- 4: Why debugger.sendCommand("DOM.getDocument") not working from rendered process electron/electron#5443
- 5: https://chromedevtools.github.io/devtools-protocol/tot/Page/
- 6: [Bug]: Debugger not hit/paused in DevTools when using CDP and dynamically creating IFrame element electron/electron#35478
- 7: chromium/chromium@6f320e2
- 8: Page.addScriptToEvaluateOnNewDocument doesn't work as expected puppeteer/puppeteer#4126
🌐 Web query:
site:github.com/electron/electron Page.addScriptToEvaluateOnNewDocument debugger runs immediately existing pages
💡 Result:
The Chrome DevTools Protocol (CDP) method Page.addScriptToEvaluateOnNewDocument is designed to register a script that will be automatically evaluated in any new document or frame upon creation, specifically before any other scripts are executed in that document [1][2][3]. Crucially, this method does not affect pages that are already loaded or currently active when the command is sent [1][4][5]. It only applies to future navigations or new document creations occurring after the script has been registered [2][6]. If you need to execute JavaScript in a page that is already loaded, you should use Runtime.evaluate via the DevTools debugger session or, in the context of Electron, methods like webContents.executeJavaScript [7][8][9][10]. Because executeJavaScript also runs asynchronously and waits for the page content to be ready if it has not yet loaded, it is typically the correct approach for existing environments [7][8]. If you are using this specifically for debugging purposes and require the debugger to break on the very first line of a page's script, ensure you register the script using Page.addScriptToEvaluateOnNewDocument before initiating the navigation [1]. If the page is already loaded, reloading the page after calling Page.addScriptToEvaluateOnNewDocument will trigger the evaluation of the registered script during the new page load [2][11].
Citations:
- 1: better documentation for Debugger.sendCommand callback behavior electron/electron#14822
- 2: [Bug]: Debugger is unable to pause early in new browser windows electron/electron#40734
- 3: preload scripts are being injected into _blank windows electron/electron#6991
- 4: https://github.com/electron/electron/blob/master/shell/browser/api/electron_api_debugger.cc
- 5: Page.frameAttached Chrome Devtools Protocol events are not being dispatched electron/electron#46048
- 6: https://github.com/electron/electron/blob/1ad832a4/shell/renderer/electron_renderer_client.cc
- 7: [Bug]: webContents.executeJavaScript will never execute/fail when no content has been loaded. electron/electron#31792
- 8: docs: remind user executeJavaScript will not run immediately. electron/electron#19129
- 9: https://github.com/electron/electron/blob/da3dbdcb9bb98471cede64ddd311dc8b4c378e62/docs/api/web-contents.md
- 10: https://github.com/electron/electron/blob/5-0-x/docs/api/web-frame.md
- 11: [Bug]: When calling BrowserWindow.webContents.reload or BrowserWindow.loadURL, the execution order of the Chrome extension is incorrect. electron/electron#43221
🌐 Web query:
Electron debuggers debugger on navigate detach sendCommand Page.addScriptToEvaluateOnNewDocument
💡 Result:
In Electron, when using the webContents.debugger API, navigation events can impact the debugger session [1][2]. Historically, Electron's internal implementation would automatically disconnect and reconnect the debugger whenever the RenderFrameHost changed (which occurs upon navigation), causing the loss of queued protocol messages and resetting the session state [1][2]. Regarding the specific interaction with Page.addScriptToEvaluateOnNewDocument: 1. Persistence Across Navigation: Commands sent via debugger.sendCommand are generally bound to the current DevTools session. If a session is disconnected and reconnected during navigation, settings such as Page.addScriptToEvaluateOnNewDocument may be cleared because the target environment has effectively reset [1][2]. 2. Debugger Stability: Recent improvements in Electron (specifically addressing issues where DevTools network events were dropped during navigation) have moved away from unconditionally disconnecting/reconnecting on every RenderFrameHost change [2]. This should improve the stability of commands like Page.addScriptToEvaluateOnNewDocument across navigations, provided the debugger session remains active [2]. 3. Implementation Detail: Page.addScriptToEvaluateOnNewDocument is a Chrome DevTools Protocol (CDP) method [3]. When you call it via debugger.sendCommand('Page.addScriptToEvaluateOnNewDocument', { source: '...' }), the script is registered with the browser. If the debugger session is explicitly detached or lost, that registration is typically lost. If you encounter issues where scripts fail to execute after navigation, ensure your debugger session is not being implicitly detached. You can monitor this by listening for the detach event on your debugger instance [4][5]: win.webContents.debugger.on('detach', (event, reason) => { console.log('Debugger detached:', reason); }); If the debugger is detaching during navigation, you may need to re-issue your Page.addScriptToEvaluateOnNewDocument command after the navigation completes or after re-attaching the debugger [4][5].
Citations:
- 1: Page.frameAttached Chrome Devtools Protocol events are not being dispatched electron/electron#46048
- 2: fix: devTools network events dropped on RenderFrameHost swap electron/electron#51959
- 3: https://chromedevtools.github.io/devtools-protocol/tot/Page/
- 4: https://github.com/electron/electron/blob/main/docs/api/debugger.md
- 5: https://electronjs.org/docs/latest/api/debugger
🌐 Web query:
Electron WebContents debugger sendCommand returns Promise if debugger attaching command not yet attached
💡 Result:
The Electron debugger.sendCommand method returns a Promise regardless of whether the debugger is attached [1][2]. However, if you attempt to use sendCommand while the debugger is not attached, the promise will be rejected [1][2]. According to the official Electron documentation, sendCommand returns a promise that resolves with the command's response or is rejected if the command fails [1][2]. Sending a command without first calling debugger.attach() is considered a failure, resulting in a rejected promise. To correctly use the debugger, you must ensure the debugger is attached to the target webContents before invoking sendCommand [3]. You can verify the attachment status using debugger.isAttached() [3]. Example of correct usage: const { BrowserWindow } = require('electron'); const win = new BrowserWindow; const { debugger: dbg } = win.webContents; async function runDebuggerCommand { try { // 1. Attach the debugger await dbg.attach('1.3'); // 2. Send commands const response = await dbg.sendCommand('Network.enable'); console.log('Command successful', response); // 3. Detach when finished await dbg.detach; } catch (err) { console.error('Debugger operation failed:', err); } } runDebuggerCommand; If you attempt to call sendCommand without attach, or if the attachment fails (for instance, because another debugger or DevTools instance is already attached), the promise returned by sendCommand will reject, and you should handle this error using standard try/catch or .catch() blocks [1][3][2].
Citations:
- 1: https://github.com/electron/electron/blob/main/docs/api/debugger.md
- 2: https://electronjs.org/docs/latest/api/debugger
- 3: Why debugger.sendCommand("DOM.getDocument") not working from rendered process electron/electron#5443
Register the guard before the first guest navigation.
injectAntiDetection() queues Page.addScriptToEvaluateOnNewDocument after attach(), so it does not wait for the script registration to complete. If the initial URL contains inline window.close(), it can execute before the guard is installed. The dom-ready fallback runs after inline scripts and does not cover that case.
Defer or block initial navigation until the guard registration succeeds. Add an Electron regression page that calls window.close() in its initial inline script.
Greptile SummaryThis PR fixes a crash caused by a stale webContents pointer surviving guest destruction: link-created tabs that called
Confidence Score: 5/5Safe to merge — both the stale-map bug and the premature window.close race are addressed at the correct layers, with no regressions to the existing guest lifecycle. The two root causes of the crash are directly fixed: the reverse map is now cleaned up on guest destruction with a safe identity guard, and the window.close no-op is installed in the page's main world before any inline script can execute. The allowWindowClose flag is correctly threaded through creation, state, schema, and session restore. The changes are tightly scoped, well-commented, and backed by targeted unit tests and a new Playwright regression covering the exact reported crash scenario. Files Needing Attention: No files require special attention.
|
| Filename | Overview |
|---|---|
| src/main/browser/browser-manager.ts | Fixes stale-pointer crash: cleanupGuestPolicyAttachment now removes both forward (tabIdByWebContentsId) and reverse (webContentsIdByTabId) map entries, guarded so a live replacement guest is never evicted; retireStaleGuestWebContents removes the now-redundant duplicate delete. |
| src/main/window/createMainWindow.ts | will-attach-webview now inspects params.preload and webPreferences.preload for the sentinel marker; injects guard preload for ordinary guests, strips marker and allows native close for CLI-allowed guests. |
| src/preload/browser-window-close-installation.ts | Installs window.close as a non-configurable, non-writable no-op via Object.defineProperty with a writable-assignment fallback; silently swallows failures for the already-locked case. |
| src/preload/browser-window-close.ts | Standalone sandboxed preload entry point that calls contextBridge.executeInMainWorld to install the window.close guard in the page's main world before any inline script runs. |
| src/shared/browser-window-close-policy.ts | Defines the synthetic sentinel file:// URL used as a one-time marker to signal CLI-allowed window.close across the renderer→main will-attach-webview boundary. |
| src/renderer/src/components/browser-pane/browser-page-webview.ts | Stamps the sentinel preload URL on the webview element before attach when allowWindowClose is true, consumed and removed by createMainWindow in will-attach-webview. |
| src/renderer/src/store/slices/browser.ts | Propagates allowWindowClose through createBrowserTab/createBrowserPage option chains and through session restore paths for both first and subsequent pages. |
| src/shared/workspace-session-schema.ts | Adds optional allowWindowClose boolean to the browser page Zod schema so CLI tabs restore with their intended close policy across sessions. |
| tests/e2e/browser-tab.spec.ts | Adds two Playwright e2e tests: one proves that a link-created tab calling window.close() does not crash tab switching; the other proves explicitly-allowed tabs can still replace window.close. |
| electron.vite.config.ts | Registers browser-window-close-preload as a separate build entry so the sandboxed preload is emitted as a standalone CJS file without Rollup helper chunks. |
Reviews (2): Last reviewed commit: "fix(browser): preserve explicit window c..." | Re-trigger Greptile
|
looking into it |
|
thanks for reporting. looking into it |
* fix(browser): prevent window.close guest crashes * fix(browser): guard close before inline scripts * fix(browser): preserve explicit window close policy
Summary
window.close()during document creation and afterdom-ready.target=_blankflow.ELI5
An embedded browser tab is like a small browser window inside Orca. A link-created tab ran
window.close(), and although the close was supposed to be blocked, Orca kept a pointer to the guest after Chromium had destroyed it. Clicking another tab made Orca use that dead pointer and crash. The fix blockswindow.close()early for normal embedded tabs and removes stale pointers when guests are destroyed. CLI-created tabs intentionally keep their existing self-close behavior.Fixes #11763
Validation
pnpm run typecheckpassed.pnpm exec electron-vite build --mode e2epassed.SKIP_BUILD=1 pnpm exec playwright test tests/e2e/browser-tab.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --grep 'blocked window.close'passed.Full lint still reports two unrelated pre-existing duplicate-import warnings in
tests/tools/benchmarks/terminal-cold-park-resource-bench.mjsandtests/tools/benchmarks/terminal-cold-park-reveal-bench.mjs.