How can I get value from JavaScript variable using HTMLUnit
framework? Like I have var important = "Few important words"
and I want to get this string.
Asked
Active
Viewed 2,260 times
1 Answers
3
If the variable is globall-scoped, I would try using the executeJavaScript(...)
function.
But if the variable is not globally-scopes, I think you're out of luck:
(function(){
var important = "Few important words";
// ...
}());
In that case you may have to rely on screen-scraping or actually parsing the HTML/JavaScript to extract the information. Good luck.
See also How do I extract a long string of text from some JavaScript on a web page using BeautifulSoup? - that question is about Python, but the final answer - "use regular expressions" - seems like it could work in Java. Parsing HTML/JavaScript with a RegEx is not the ideal solution, but if you have no other options...

Community
- 1
- 1

Richard JP Le Guen
- 28,364
- 7
- 89
- 119
-
I see, but when I use `System.out.println(page.executeJavaScript("mobile").toString());` I get `ScriptResult[result=null page=HtmlPage(*url deleted by me*)@1990889081]`. What should I do? While executing `alert(window["mobile"]);` in Google Chrome there is window with correct value. BTW. It is an object, I didn't mention it before. – wirher Mar 15 '13 at 19:33
-
The return type of `executeJavaScript(...)` is [`ScriptResult`](http://htmlunit.sourceforge.net/apidocs/com/gargoylesoftware/htmlunit/ScriptResult.html). Read the API for `ScriptResult`! Maybe `getJavaScriptResult().toString()` will give better results. – Richard JP Le Guen Mar 15 '13 at 19:48
-
.toString() represents whole object as string so value is "null" which means nothing. Sadly using `getJavaScriptResult` doesn't help either. – wirher Mar 15 '13 at 20:30
-
I take it `mobile` is the variable you're trying to access? Perhaps `page.executeJavaScript("return mobile").getJavaScriptResult().toString()` - I would assume that in order for `getJavaScriptResult` to return a non-null value the JS snippet has to return a value. – Richard JP Le Guen Mar 15 '13 at 20:32
-
Using `System.out.println(page.executeJavaScript("return mobile").getJavaScriptResult());` gives "null" in console. With `.toString()` I get NullPointerException. And yes, mobile is boolean variable (I'm trying to get value from simple type first, then I will play with object one). – wirher Mar 15 '13 at 20:35
-
@wirher : Could you resolve your problem then ? I am trying to get the result of a var, which is json to save the json. No chance. Thx for a quick response. – mmx73 Mar 18 '15 at 15:59
-
@mmx73 Actually I used regex to extract data I wanted back then. – wirher Mar 18 '15 at 18:16