Browser

Script Injection

Register a script that runs automatically on every new document load (before page scripts run), and remove it later.

Register a script that runs automatically on every new document load (before page scripts run), and remove it later.

InjectScript registers JavaScript (a raw string, or one or more files via GPALFile) so it executes at the very start of every subsequent document load, persisting across navigations until ClearInjectedScripts is called. It can be called before the first GoTo/Get - so it is active from the very first page load - or at any later point in the workflow, in which case it applies to subsequent navigations. This is a general-purpose extensibility primitive (polyfills, instrumentation hooks, page-environment patches), not a stealth feature.

WARNING

When the browser is driven via OttoMagic, InjectScript depends on the browser extension's userScripts API (chrome.userScripts / browser.userScripts). In Chrome and Edge, this API is hidden until enabled once for the extension: 1. Open chrome://extensions (or edge://extensions). 2. Enable 'Developer mode' (top-right toggle). 3. Find the OttoMagic extension and click 'Details'. 4. Enable the 'Allow User Scripts' toggle. Firefox does not require this step. When driving the browser via Selenium or Puppeteer, InjectScript uses CDP directly (Chrome/Edge only) and this manual setup is not needed.

Examples

GPAL Fluent: High-level fluent C# API

//InjectScript returns the fluent browser interface, so it can be chained before the first GoTo/Get (applies from the first page load) or inserted anywhere later (applies to subsequent navigations only - it does not affect the currently loaded page). If a GPALFile resolves to multiple filenames, each file's contents is loaded and registered as its own injected script. ClearInjectedScripts removes every script registered this way.

// active from the very first page load GPAL.Browser() .InjectScript("window.__hooked = true;") .GoTo("https://example.com"); // inject from one or more files (GPALFile.WithFileName supports wildcards) browser.InjectScript(GPAL.File.WithFileName("hooks/*.js")); // stop injecting on future navigations browser.ClearInjectedScripts() .GoTo("https://example.com/clean");