3

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.

3

2 Answers 2

2

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;");
Sign up to request clarification or add additional context in comments.

1 Comment

YES! That's it! :) Thanks a lot!
0

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...

1 Comment

oh, yes, that is working solution :) thanks! ps: but still mostly perfect would be get exactly params.authKey value, as i can do this from Firebug console...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.