0

I want to get the value of a particular Javascript variable hard-coded in a html page. Visit the test-case with the following instructions:

  • Go to the website : http://www.headphonezone.in/
  • Open console
  • Type : Shopify.theme
  • Output is : Object {name: "Retina", id: 8528293, theme_store_id: 601, role: "main"}
  • Type : Shopify.theme.theme_store_id
  • Output is : 601

The above response comes from the script given below, which is present in all the Shopify stores.

<script>
//<![CDATA[
      var Shopify = Shopify || {};
      Shopify.shop = "headphone-zone.myshopify.com";
      Shopify.theme = {"name":"Retina","id":8528293,"theme_store_id":601,"role":"main"};

//]]>
</script>

How to write a java code to get the value of Shopify.theme.theme_store_id field and store it?

Eric Leibenguth
  • 4,167
  • 3
  • 24
  • 51
proxima
  • 323
  • 2
  • 15
  • 1
    Java (a server-side compiled language) has nothing to do with JavaScript (script language usually executed client-side). They just have similar-sounding names. You would have to send/receive data between your client (e.g. the browser) and your web server, and serialize/deserialize it. – Ted Nyberg Jul 06 '15 at 09:21
  • 1
    Do you want to execute the Javascript code and access Javascript objects? Or just parse the html response and extract the data included within the script tags? – Eric Leibenguth Jul 06 '15 at 09:21
  • @EricLeibenguth Any one would work. Finally, I need the value in my java program to run further works. Kindly tell me how can I parse html to get the required data by Java. – proxima Jul 06 '15 at 09:28
  • @TedNyberg I do understand the difference. But I am not able to know how I can get the required data and store in my database. – proxima Jul 06 '15 at 09:29

1 Answers1

2
  • Get the html page as a String (see this post)
  • Detect the "Shopify.theme" keyword with a regex:

.

String patternString = "Shopify.theme\\s*=\\s*.*theme_store_id\\"\\:(\\d+)";
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(text);

String themeStoreId;
while (matcher.find()) {
    themeStoreId = matcher.group(1);
}
Community
  • 1
  • 1
Eric Leibenguth
  • 4,167
  • 3
  • 24
  • 51
  • To clarify - this code is extracting the requested string from the HTML page, but does not care at all that it is "JavaScript" or otherwise interpret it in any way. To OP: tags 'JavaScript' and 'Object' are not needed. – tucuxi Jul 06 '15 at 10:31
  • Thanks, I used `String patternString = "(?i)(Shopify.theme)(.+?)(;)";` worked well!! – proxima Jul 06 '15 at 11:10