Scripting

Execute JavaScript

Run arbitrary JavaScript in the page context.

Run arbitrary JavaScript in the page context.

Executes the supplied JavaScript expression in the context of the current page and returns the result, either as a raw object or as a string depending on which variant is used. Supported when the browser session uses Selenium (IJavaScriptExecutor) or Puppeteer (CDP Runtime.evaluate).

WARNING

ExecuteJavaScriptObj and ExecuteJavaScriptStr are not supported when the browser session uses OttoMagic - running arbitrary, dynamically-constructed JavaScript from a browser extension's content/background script is blocked by Manifest V3's content security policy. Calling either method on an OttoMagic session publishes a GPALEventType.ERROR event and returns null; GPAL.MagicHelper.ExecuteJavaScript has been removed. For code that needs to run on every page in an OttoMagic session, use InjectScript instead - it registers the script up front (via the extension's userScripts API) rather than evaluating an arbitrary string on demand.

Examples

GPAL Fluent: High-level fluent C# API

browser.ExecuteJavaScriptStr("return document.title"); string result = browser.JavaScriptResultStr; // or, to get the raw object result browser.ExecuteJavaScriptObj("return document.title"); object objResult = browser.JavaScriptResultObj;

Puppeteer Client: Puppeteer-style C# client

browser.PuppeteerClient.ExecuteJavaScript("return document.title").Execute();

Puppeteer Communicator: Low-level communicator

await browser.PuppeteerCommunicator.ExecuteJavaScript("return document.title", sessionId);

REST Client: Direct REST/HTTP client

//This low-level RESTClient primitive and its ApiEndpoint.ExecuteJavaScript route still exist for direct protocol use, but GPAL's fluent ExecuteJavaScriptObj/ExecuteJavaScriptStr no longer call into it for OttoMagic sessions - see the warning above.

GPAL.OttoMagicClient.ExecuteJavaScript("return document.title").Execute();