0

In a HTML page, i want to pick the value of a javascript variable. Below is the snippet of HTML page.

<script type="text/javascript">
$(function() {
  $.ajaxSetup({
    beforeSend: function(xhr) {
      xhr.setRequestHeader('X-MOON-EXPIRED', "1445350653");
      xhr.setRequestHeader('X-MOON-TOKEN', "10dafe974cc156d2d3b7fd9bb1e4e3ed");
    }
  });
});
</script>

My aim is to read the value of variable X-MOON-EXPIRED and X-MOON-TOKEN from this page using Java. Thanks.

4
  • You might be able to get by here with a regex or something. Commented Oct 20, 2015 at 14:30
  • 2
    Possible duplicate of Javascript parser for Java Commented Oct 20, 2015 at 14:30
  • Does the page with the javascript on it belong to you, or are you scraping it off someone else's page? Commented Oct 20, 2015 at 15:05
  • Based on the answer below, it appears that the question is NOT UNCLEAR. Based on that, I think this "hold" is unreasonable. Vote to reopen. Commented Oct 20, 2015 at 18:27

1 Answer 1

2
import java.util.regex.*;
Pattern p1 = Pattern.compile("X-MOON-EXPIRED', \"([^\"]*)\"");
Pattern p2 = Pattern.compile("X-MOON-TOKEN', \"([^\"]*)\"");
String html = "<script type=\"text/javascript\"> $(function() {   $.ajaxSetup({     beforeSend: function(xhr) {       xhr.setRequestHeader('X-MOON-EXPIRED', \"1445350653\");       xhr.setRequestHeader('X-MOON-TOKEN', \"10dafe974cc156d2d3b7fd9bb1e4e3ed\");     }   }); }); </script>";
Matcher m1 = p1.matcher(html);
Matcher m2 = p2.matcher(html);
if (!m1.find() || !m2.find()) {
    throw new Exception("Didn't match");
}
System.out.println(String.format("X-MOON-EXPIRED=%s, X-MOON-TOKEN=%s", m1.group(1), m2.group(1)));

Prints:

X-MOON-EXPIRED=1445350653 X-MOON-TOKEN=10dafe974cc156d2d3b7fd9bb1e4e3ed
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.