not able to get the value in script tag

I want to get the visitor_id in the script tag.

<script>
  window.dataLayer = window.dataLayer || [];
  window.dataLayer.push({
    "currentVer": "v137.4",
    "is_internal": false,
    "CBPageType": "Recommendations",
    "is_jdp": false,
    "site_id": "cbnsv",
    "user_status": "Unknown",
    "search_engine": "solr_v4",
    "session_id": "42d3f1b678413a86e8ed79938348d165",
    "server_pool_name": "rails",
    "ipath": "CRJR6",
    "InGlobalExperimentGroups": "LightRegistration:default|extended_top_jobs:experiment1|colab_menu:experiment1|FreeReviewCV:control|HomepageChat:default|RemoveModalExternalApply:experiment1|SourceLocation:default|internal_apply_v3:default",
    "in_global_experiment_groups": "LightRegistration:default|extended_top_jobs:experiment1|colab_menu:experiment1|FreeReviewCV:control|HomepageChat:default|RemoveModalExternalApply:experiment1|SourceLocation:default|internal_apply_v3:default",
    "in_page_experiment_groups": "LightRegistration:default|extended_top_jobs:experiment1|colab_menu:experiment1|FreeReviewCV:control|HomepageChat:default|RemoveModalExternalApply:experiment1|SourceLocation:default|internal_apply_v3:default",
    "browser_id": "X19EF84C01BB9BD92A590AC63F87B5CF5554F72399AB1C3B25092D02C262681753351F7E3AD4D7921B0B0ADDD1833CD50A",
    "visitor_id": "VXDAFEAA801C5A11EC8BCB8F02C62498172220O1",
    "visitor_classification_onet": "",
    "visitor_classification_carotene": "",
    "visitor_state": "Tracked"
  })
</script>

The visitor_id is dynamic. How can I get the visitor_id? I am using selenium. Thanks in advance.


Solution 1:

In whatever javascript executed (not loaded, you can load it before as long as it is executed afterwords) after the <script> tag of yours, you just have to do:

var visitorId = window.dataLayer[0].visitor_id;

or

var visitorId = window.dataLayer[0]["visitor_id"];

I used 0 as the index because your example only pushes one element. But in case is different you will have to use the appropriate index.

Update

To evaluate it from java when using selenium use this:

WebDriver driver = //your driver declaration here. You should already have this
// ... random selenium stuff you sure have
JavascriptExecutor js = (JavascriptExecutor) driver;
String visitorId = (String) js.executeScript("window.dataLayer[0].visitor_id");