Scripting

Execute JavaScript

Runs the supplied JavaScript in the page's own world and hands back what it produced, as a raw object or as a string depending on the variant. Every engine serves it: Selenium through IJavaScriptExecutor, Puppeteer through CDP Runtime.evaluate, and OttoMagic through the extension's userScripts.execute.

WARNING

ExecuteJavaScript via OttoMagic depends on the browser extension userScripts API (chrome.userScripts / browser.userScripts). In Chrome and Edge, this API is hidden until the user manually enables it for the extension: 1. Open chrome://extensions (or edge://extensions). 2. Enable 'Developer mode' using the toggle in the top-right corner. 3. Find the OttoMagic extension and click 'Details'. 4. Enable the 'Allow User Scripts' toggle. Without this one-time step, calls to ExecuteJavaScript via OttoMagic will fail because chrome.userScripts is undefined. Firefox does not require this manual step - browser.userScripts is available to the extension by default. This setup is not required for ExecuteJavaScript via Selenium or Puppeteer, which run the script through IJavaScriptExecutor and Runtime.evaluate.

Examples

GPAL Fluent: High-level fluent C# API

//Write it either way. Selenium's executor is a function body and wants the return; Puppeteer and OttoMagic evaluate a statement list and answer with its last value, where a return is a syntax error. GPAL runs the script as written, and only if the engine refuses the return does it wrap it in a function and run it again, so one line works on all three.

browser.ExecuteJavaScriptStr("return document.title");

MagicHelper: MagicHelper utility library

//An expression, not a statement block. The extension runs this through userScripts.execute, which takes the value of the last expression, so a top level return is a syntax error here.

string title = browser.MagicHelper.ExecuteJavaScript("document.title");

Puppeteer Client: Puppeteer-style C# client

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

Puppeteer Communicator: Low-level communicator

//Runtime.evaluate takes an expression, the same as OttoMagic does, so this side wants document.title and not return document.title.

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

REST Client: Direct REST/HTTP client

//The route the fluent call uses on an OttoMagic session, reached directly. WithCss and the element parameters mean nothing here: the script is the whole request.

browser.OttoMagicClient.ExecuteJavaScript("document.title").Execute();

💬 Ask GPAL