Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question

closed as not a real question by James Montagne, BenM, Andrew, 3nigma, Muhammad Reda Mar 15 '13 at 21:08

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.If this question can be reworded to fit the rules in the help center, please edit the question.

1 Answer 1

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

share|improve this answer
    
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. 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

Not the answer you're looking for? Browse other questions tagged or ask your own question.