DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk4 min

How to Execute JavaScript in Selenium with PHP

Run synchronous or asynchronous JavaScript in Selenium using php-webdriver, with examples for results, element arguments, context, and common errors.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

With php-webdriver/php-webdriver, call $driver->executeScript() to run synchronous JavaScript in the browser’s currently selected frame. Pass values and WebElement objects in its second argument, and use JavaScript’s return when PHP needs a result. For asynchronous browser work, use executeAsyncScript() and invoke its injected completion callback.

Run a synchronous JavaScript snippet

RemoteWebDriver provides executeScript($script, array $arguments = []). The script runs in the selected browser context, and its evaluated result is returned to PHP.

<?php

use FacebookWebDriverRemoteRemoteWebDriver;

// Assume $driver is an active RemoteWebDriver session.
$title = $driver->executeScript('return document.title;');
echo $title;

$driver->executeScript('document.body.style.backgroundColor = "red";');

The first call returns the page title because the JavaScript contains return. The second changes the current page’s background color and does not need to return a value. See the php-webdriver RemoteWebDriver API and its example command reference.

Pass values and elements safely

Supply dynamic values or located elements through the second PHP parameter, then read them from JavaScript’s arguments array. This avoids building a script by concatenating data into its source.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<?php

use FacebookWebDriverWebDriverBy;

$element = $driver->findElement(WebDriverBy::cssSelector('h1'));
$text = $driver->executeScript(
    'return arguments[0].innerText;',
    [$element]
);
echo $text;

For multiple inputs, pass them in order and use arguments[0], arguments[1], and so on. The php-webdriver examples document passing located elements to script execution and accessing them through arguments.

Use executeAsyncScript for asynchronous work

Choose executeAsyncScript() when the script must wait for asynchronous browser work. The driver adds a completion callback as the final argument and waits until your script calls it; the callback’s value becomes the PHP method result.

<?php

$result = $driver->executeAsyncScript(
    'const done = arguments[arguments.length - 1];
     setTimeout(() => done("finished"), 100);'
);
echo $result; // finished

Configure an appropriate script timeout using the timeout API for your installed php-webdriver version before running work that may take time. There is no universal timeout value established here; choose one that fits the operation and ensure every completion path calls the callback. Selenium’s asynchronous script API description also specifies that an async script must signal completion through the injected callback.

Choose the right method and browser context

Need Use Key detail
Run JavaScript that completes directly executeScript() Use JavaScript return if PHP needs a value.
Wait for asynchronous JavaScript work executeAsyncScript() Call the injected callback; configure a suitable script timeout.
Operate on another frame or window Select that browsing context first Scripts run in the currently selected frame or window.

Before execution, select the intended frame or window. Selenium’s interaction documentation describes JavaScript execution in the selected context. If you need a result from a synchronous script, explicitly return it. Complex JavaScript objects may not map to PHP in a uniform way across library and Selenium versions, so check the behavior for the versions you use rather than assuming a particular PHP representation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Practical guidance and troubleshooting

  • The script reads the wrong page or frame: verify the current URL and select the intended window or frame before calling the script.
  • PHP receives no expected value: make sure the synchronous JavaScript uses return on the desired value.
  • An element or value is missing inside JavaScript: pass it in the second PHP argument and reference the matching arguments[n] index.
  • An async script hangs or times out: check that every success and error path invokes the callback, and review the script timeout configured for the installed php-webdriver version.
  • A script-based click does not behave like a user click: JavaScript execution is page-context code, not a guarantee of equivalent user input. Prefer Selenium’s ordinary element interactions when they express the test intent; use scripts for page-context operations or state retrieval and changes.

Or skip the browser setup

If your goal is to capture a page rather than run arbitrary Selenium code, ScreenshotNeo provides a website screenshot API. One GET request returns a PNG, JPEG, WebP, or PDF, and its API accepts common screenshot parameter names to make switching easier. See the ScreenshotNeo documentation.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

ScreenshotNeo accepts cookie and consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and responses identify the page verdict and billing status in headers. Its MCP server offers take_screenshot, get_page_info, and capture_pdf for AI agents and MCP clients. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots. Sign up for 1,000 free screenshots a month with no card.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Frequently Asked Questions

Can I pass a Selenium element to executeScript() in PHP?

Yes. Pass the WebElement in the second argument array and access it in JavaScript through the corresponding arguments[n] index.

Why does executeAsyncScript() need a callback?

The driver waits for the injected final-argument callback; calling it signals completion and supplies the method’s result.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. Shenzhen desk3 min
    HONOR Expands Beyond Smartphones With Humanoid Robot RevealHONOR said it unveiled its first humanoid robot at MWC 2026 and named shopping assistance, workplace inspections, and supportive companionship as intended uses. Later Robotics D1 claims and a reported…
  2. Cupertino desk5 min
    Apple Unveils AirPods Max 2: The Upgrade That Should Have Happened Years AgoAirPods Max 2 adds H2-powered audio features and Apple claims up to 1.5× more effective ANC, but its design, Smart Case, and 20-hour battery rating are unchanged. Wired lossless audio…
  3. Cupertino desk4 min
    Apple’s OLED Touch MacBooks Are Coming—but the Dynamic Island Is the Real GambleApple has not announced an OLED touchscreen MacBook, but reports point to high-end models arriving in late 2026 or early 2027. The reported Mac Dynamic Island could be useful, but…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.