nam vo
nam vo

Reputation: 3447

ChromeWebDriver IJavaScriptExecutor to get script value?

I have a strange issue with ChromeDriver v75.0.3770.140 when I try with a url below to return a script value, and it returns a null value.

   var driver = new ChromeDriver();
    driver.Navigate().GoToUrl("https://www.6pm.com/p/adidas-team-issue-ii-sackpack-white-jersey-black-clear-lilac-purple/product/9045515/color/749092");

    IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
    var val2 = js.ExecuteScript("return window.zfcSessionId"); // work fine
    var val = js.ExecuteScript("return window.__INITIAL_STATE__;"); // nullreference

Upvotes: 1

Views: 585

Answers (1)

EylM
EylM

Reputation: 6103

From Selenium documentation:

The ExecuteScript(String,Object[] )method executes JavaScript in the context of the currently selected frame or window. This means that "document" will refer to the current document. If the script has a return value, then the following steps will be taken:

  • For an HTML element, this method returns a IWebElement
  • For a number, a Int64 is returned
  • For a boolean, a Boolean is returned
  • For all other cases a String is returned. For an array,we check the first element, and attempt to return a List<T> of that type, following the rules above. Nested lists are not supported. If the value is null or there is no return value, null is returned.

In your case, __INITIAL_STATE__ is a JSON object that does not meet any of the returning types above.

Instead of getting the JSON object from the web page, try to get the serialized string in the C# code (by executing JSON.stringify):

var val = js.ExecuteScript("return JSON.stringify(window.__INITIAL_STATE__)");

In this case, the return value is string. From here, you can deserialize it using:

dynamic data = JsonConvert.DeserializeObject(val);

Upvotes: 1

Related Questions