Mikhail Zlochevskyi
Mikhail Zlochevskyi

Reputation: 31

How to use js variable from Java WebDriver on Firefox

Main goal is to get javascript element authKey into Java code. Here is code:

index.html:

...
      <script type="text/javascript">

        var params = {
            authKey: "abc"
        };

        Main.init("#content", params);
    </script>
...

main.java:

    public static void main(String[] args) throws InterruptedException {

        WebDriver d = new FirefoxDriver();
        d.get("***/index.html");
   //     System.out.println(" var " + d.findElement(By.xpath("/html/body/script[3]")));
        Thread.sleep(3000);
        JavascriptExecutor jse = (JavascriptExecutor) d;
//        System.out.println(jse.executeAsyncScript("document.URL"));
        Object val = jse.executeScript("return params.authKey;");
        d.quit();
    }

I'm always getting something like:

Exception in thread "main" org.openqa.selenium.JavascriptException: ReferenceError: **params is not defined**
Build info: version: '3.0.1', revision: '1969d75', time: '2016-10-18 09:49:13 -0700'
System info: host: 'Mikhails-MacBook-Pro.local', ip: '10.10.20.139', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.11.6', java.version: '1.8.0_111'
Driver info: org.openqa.selenium.firefox.FirefoxDriver

I've tried different ways to get this authKey parameter, without return, as function, but still nothing... Could someone help with that?

Thanks in advance.

UPD: Solution https://stackoverflow.com/a/40936063/6809155 works, but still looking for native js solution to get exactly params.authKey parameter, because in future there could be a lot of params.

Upvotes: 3

Views: 564

Answers (2)

Florent B.
Florent B.

Reputation: 42528

There's a scope issue depending on the version of Firefox. It could be that your variable is sand boxed in window.wrappedJSObject.

Try this:

Object val = jse.executeScript(
  "return (window.params || window.wrappedJSObject.params).authKey;");

Upvotes: 2

Grasshopper
Grasshopper

Reputation: 9058

Assuming you got only one script tag or this is the first one.

    WebElement scr = driver.findElement(By.tagName("script"));
    System.out.println(scr.getAttribute("innerHTML"));
    System.out.println(scr.getAttribute("innerText"));

You should get the following output using either of the above two attributes.

var params = {
     authKey: "abc"
};

Main.init("#content", params);

Parse the output to get the authKey...

Upvotes: 0

Related Questions