Skip to content

Conversation

Copy link

Copilot AI commented Aug 6, 2025

The ExecuteScript method was throwing InvalidCastException: Object must implement IConvertible when JavaScript returned primitive values like numbers. This occurred because Playwright's EvaluateAsync returns JsonElement objects, but Selenium expects native .NET types that implement IConvertible.

Problem:

IWebDriver driver = PlaywrightWebDriver.Create();
var result = driver.ExecuteScript("return 5");
Console.WriteLine(result); // Throws: Script returned a value, but the result could not be cast to the desired type

Root Cause:

  • Playwright's EvaluateAsync returns JsonElement with ValueKind = Number : "5"
  • Selenium tries to cast this JsonElement to native types
  • JsonElement doesn't implement IConvertible, causing the exception

Solution:
Added JsonElementConverter.ConvertToNativeType() that converts JsonElement results to appropriate native .NET types:

  • JSON numbers → int, long, double, or decimal (as appropriate)
  • JSON strings → .NET string
  • JSON booleans → .NET bool
  • JSON null → .NET null
  • JSON arrays → .NET object[] (with recursive conversion)
  • JSON objects → .NET Dictionary<string, object?>
  • Non-JsonElement values → pass through unchanged (preserves existing behavior)

Updated ExecuteScript and ExecuteAsyncScript methods to apply this conversion after getting results from Playwright, ensuring full Selenium compatibility while maintaining backward compatibility.

After the fix:

var result = driver.ExecuteScript("return 5");
Console.WriteLine(result); // Prints: 5 (as System.Int32)

Fixes #108.


💬 Share your feedback on Copilot coding agent for the chance to win a $200 gift card! Click here to start the survey.

Copilot AI changed the title [WIP] "Script returned a value, but the result could not be cast to the desired type" Fix ExecuteScript casting exception by converting JsonElement to native types Aug 6, 2025
Copilot AI requested a review from thomhurst August 6, 2025 08:07
@thomhurst thomhurst marked this pull request as ready for review August 6, 2025 08:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

"Script returned a value, but the result could not be cast to the desired type"

2 participants