Skip to content

[Feature] Add @inject-into page support and direct main-world bridge execution #1833

Description

@dartsc

Pre-check

  • I have searched existing issues and confirmed that this is not a duplicate feature request.
  • Where possible, I have checked the latest stable or beta version and confirmed that this feature is still unavailable.
  • I have confirmed that this is a request for a new or improved feature, not a bug report about an existing feature.

The Problem You Want to Solve

Scripts that declare elevated GM_* privileges are isolated within an extension sandbox / USER_SCRIPT world. While this matches strict MV3 isolation standards, it creates annoyance for complex scripts that are from tampermonkey/violentmonkey who come for a more powerful experience.

Proposed Solution

unsafeWindow Serialization Overhead: Complex object sharing and passing direct function references across the sandbox boundary frequently trigger permission denials or context mismatches under Chromium's stricter object wrappers.

Developers must construct manual window.postMessage listeners and JSON serialization pipelines solely to expose GM_getValue, GM_setValue, or value change listeners to scripts operating on the target page.

Execution Timing at document-start: Synchronous storage lookups (GM_getValue) frequently race against the extension's bridge initialization, returning undefined on early ticks.

Support // @inject-into Metadata Directive:

page: Inject the userscript directly into the host document's execution context (MAIN world). Expose granted GM_* and CAT_* methods directly on the script scope by binding them to internal message-passing dispatchers automatically.

content: Force execution within the isolated extension sandbox (current standard behavior).

auto: Default resolution based on @grant directives.

Synchronous Storage Pre-Hydration:

For scripts running at document-start with @inject-into page or isolated worlds, ensure the in-memory storage cache is fully resolved before user code execution begins.

Per-Script Setting Toggle:

In the script editor/dashboard, add an advanced toggle to override injection target: "Run in Page Context (MAIN World)".

ScriptCat Version

v1.5.0

Additional Information

No response

Activity

  1. added theissue type on Nov 7, 2026
  2. CodFrm commented on Nov 9, 2026

    @CodFrm
    Member

    Thanks for the write-up! ScriptCat's default behavior is already @inject-into page. Am I misunderstanding what you're asking for?

    • Default (page): the script runs in the page's MAIN world even when it has @grants. GM APIs are bridged automatically, so you don't need your own postMessage layer, and unsafeWindow is the page's real window.
    • @inject-into content runs the script in the isolated world, for example to get around a strict CSP. In that mode the script can't reach the page's window.
    • GM_getValue is synchronous. Values are loaded before the script runs. Add @early-start with @run-at document-start to run even before the page's own scripts.

    Examples:

    If you're seeing permission errors or undefined early on, please share a minimal script, the site, and your browser version, and we'll look into it.

  3. dartsc commented on Nov 11, 2026

    @dartsc
    Author

    RESPONSE CREATED BY GEMINI ARGON:
    Thanks @CodFrm! You're right that ScriptCat defaults to the MAIN world (@inject-into page) and pre-loads GM_getValue, which is awesome.

    The issue I'm running into with existing Tampermonkey scripts is specifically how the Proxy sandbox (with(proxyContext)) traps property mutations on window whenever any @grant is enabled, along with @run-at document-start timing when @early-start isn't explicitly added.

    Here are the 3 specific cases where unmodified Tampermonkey scripts break in ScriptCat:

    1. window.fetch = ... / Object.defineProperty(window, ...) is trapped in the Proxy sandbox when @grant is active
      Even though the script runs in the MAIN world, as soon as @grant GM_getValue is added, ScriptCat wraps execution in createProxyContext where window !== unsafeWindow.

    Many Tampermonkey scripts hook page globals using window.fetch = ..., window.WebSocket = ..., or Object.defineProperty(window, ...) while also using GM_getValue. In ScriptCat, the Proxy set and defineProperty traps write those changes onto the isolated sandbox target (ownContext) instead of forwarding the mutation to the real window (unsafeWindow), so the page's actual fetch / WebSocket never gets hooked unless you manually rewrite the script to use unsafeWindow..

    Minimal Repro Script:

    JavaScript
    // ==UserScript==
    // @name Repro: Proxy traps window.fetch hook when @grant is used
    // @namespace http://tampermonkey.net/
    // @Version 1.0
    // @match https://example.com/*
    // @run-at document-start
    // @grant GM_getValue
    // ==/UserScript==

    const origFetch = window.fetch;
    window.fetch = async function (...args) {
    console.log("[Userscript] Intercepted fetch:", args[0]);
    return origFetch.apply(this, args);
    };

    // Trigger a fetch from the real page context:
    unsafeWindow.eval(fetch("https://example.com/").catch(() => {}));

    // Expected (Tampermonkey raw / page mode): "[Userscript] Intercepted fetch: https://example.com/" is logged.
    // Actual in ScriptCat: Nothing is logged because window.fetch = ... only mutated the Proxy sandbox target, not unsafeWindow.fetch!
    2. @run-at document-start without @early-start loses the race against inline scripts
    In Tampermonkey, @run-at document-start (even with GM_getValue) runs synchronously before inline scripts. Because standard Tampermonkey scripts from GreasyFork only have // @run-at document-start and don't include ScriptCat's custom // @early-start tag, their hooks often execute after the page's initial inline scripts have already cached window.fetch or WebSocket.

    1. Implicit unsafeWindow when other @grants are declared
      In Tampermonkey, if a script declares // @grant GM_getValue (and forgets to explicitly add // @grant unsafeWindow), unsafeWindow is still exposed. In ScriptCat, omitting @grant unsafeWindow leaves unsafeWindow undefined when other grants are active.

    Proposed Fix (Happy to submit a PR!)
    In src/app/service/content/create_context.ts:

    Always expose unsafeWindow in createContext even if @grant unsafeWindow wasn't explicitly listed alongside other @grants.

    Support @sandbox raw (or default in @inject-into page mode) where the Proxy set and defineProperty traps mirror writes for non-GM/non-sandbox properties (like fetch, XMLHttpRequest, WebSocket, etc.) to globalThis:

    TypeScript
    // Inside createProxyContext set trap:
    if (
    forwardPageGlobals &&
    !isSandboxOnlyKey(prop) &&
    (prop in globalThis || !(prop in target))
    ) {
    try {
    (globalThis as any)[prop] = value;
    } catch (_) {}
    }
    Optionally allow a setting (or default) to treat @run-at document-start as @early-start for better out-of-the-box compatibility with existing GreasyFork scripts.

  4. dartsc commented on Nov 11, 2026

    @dartsc
    Author
  5. njstalker-sys commented on Nov 11, 2026

    @njstalker-sys

    Oh and this is dartsc but I am on a different account, here's an example of errors Ive encountered before:
    2026-11-10 14:37:57 [error] messageHandle error {"env":"service_worker","service":"messageServer","error":"script is not found"}
    2026-11-10 14:37:57 [error] messageHandle error {"env":"scripting","service":"messageServer","error":"script is not found"}
    2026-11-10 14:37:58 [error] messageHandle error {"env":"service_worker","service":"messageServer","error":"script is not found"}
    2026-11-10 14:37:58 [error] messageHandle error {"env":"scripting","service":"messageServer","error":"script is not found"}
    2026-11-10 14:37:59 [error] messageHandle error {"env":"service_worker","service":"messageServer","error":"script is not found"}
    2026-11-10 14:37:59 [error] messageHandle error {"env":"scripting","service":"messageServer","error":"script is not found"}
    2026-11-10 14:38:00 [error] messageHandle error {"env":"service_worker","service":"messageServer","error":"script is not found"}
    2026-11-10 14:38:00 [error] messageHandle error {"env":"scripting","service":"messageServer","error":"script is not found"}
    2026-11-10 14:38:01 [error] messageHandle error {"env":"service_worker","service":"messageServer","error":"script is not found"}
    2026-11-10 14:38:01 [error] messageHandle error {"env":"scripting","service":"messageServer","error":"script is not found"}
    2026-11-10 14:38:02 [error] messageHandle error {"env":"service_worker","service":"messageServer","error":"script is not found"}
    [object Object]
    2026-11-10 14:38:02 [error] messageHandle error {"env":"scripting","service":"messageServer","error":"script is not found"}
    Uncaught (in promise) script is not found
    Error: script is not found
    2026-11-10 14:38:03 [error] messageHandle error {"env":"service_worker","service":"messageServer","error":"script is not found"}
    Uncaught ReferenceError: updateAutoRunDelayVisibility is not defined
    Failed to fetch opening book: TypeError: Failed to fetch
    chrome.runtime.lastError in chrome.tabs.sendMessage: [object Object]
    TypeError: Cannot read properties of undefined (reading 'data')

  6. CodFrm commented on Nov 16, 2026

    @CodFrm
    Member

    @dartsc Sorry, I’m just seeing this now.

    I tested the behaviors you described and didn't find any difference between Tampermonkey and ScriptCat. Could you share more details? Is your Tampermonkey using any non-default settings (e.g. inject mode, sandbox mode)?

    1. window.fetch = ... with @grant: I ran your exact repro in Tampermonkey and got the same result as ScriptCat — window !== unsafeWindow, and the page's fetch isn't hooked. Use unsafeWindow.fetch = ....
    2. document-start: same as Tampermonkey's default ("as fast as possible", not guaranteed before inline scripts). Add @early-start, or enable it per script in the script settings, if you need to run before the page.
    3. Implicit unsafeWindow: can't reproduce — with only @grant GM_getValue, unsafeWindow is available. Please share a script if you see otherwise.

    @njstalker-sys the script is not found errors usually mean the page is still running an old instance of a script that has since been deleted or reinstalled — its GM API calls can no longer find the script. Refreshing the page should stop them. If it keeps happening after a refresh, please open a separate bug report with the script (link or minimal code), the site URL, your browser + version, and the steps that trigger it.

    // ==UserScript==
    // @name         1833 #1: window write vs page window
    // @namespace    repro-1833
    // @version      1.0
    // @match        https://example.com/*
    // @run-at       document-start
    // @grant        GM_getValue
    // ==/UserScript==
    
    const origFetch = window.fetch;
    window.fetch = function (...args) {
      console.log("[1833] intercepted fetch:", args[0]);
      return origFetch.apply(this, args);
    };
    Object.defineProperty(window, "__repro1833", { value: 1, configurable: true });
    
    console.log("[1833] window === unsafeWindow:", window === unsafeWindow);
    console.log("[1833] page fetch hooked:", unsafeWindow.fetch === window.fetch);
    console.log("[1833] defineProperty reached page:", "__repro1833" in unsafeWindow);
    
    // Fire a fetch from the page's own world
    const s = document.createElement("script");
    s.textContent = `fetch(location.href + "?from-page").catch(() => {})`;
    (document.head || document.documentElement).appendChild(s);
    s.remove();
    QQ_2026-11-16_10-32-44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions