1

I need to automate web analytics and for that I need to trigger "Google Tag Manager" GTM script from java code. e.g.

(window,document,'script','dataLayer','GTM-KWW5SS');

  • I can goto chrome console and type dataLayer, press ENTER key to see the values

How can I do this from Java code ?

vikramvi
  • 3,312
  • 10
  • 45
  • 68
  • I'm not quite sure what you are asking, but it sounds like you are looking for something like Selenium webdriver (an automation tool that can call a website and execute scripts there). It has a function that can return the value of javascript variables in the page. My only experience is in Python so I can't help with the Java part, but searching for "Selenium Webdriver Java" on SO should give you some results. – Eike Pierstorff Nov 21 '17 at 14:55
  • @EikePierstorff I did search but couldn't find Java solution to call javascript object and extract values. Please share your python solution here – vikramvi Nov 21 '17 at 15:53
  • There is a question/answer that might help here: https://stackoverflow.com/questions/11430773/how-to-use-javascript-with-selenium-webdriver-java. In Python you can use the executeScript to pass "return " in as a parameter and it returns the value for use in the python programm. I assume it works similar in Java. – Eike Pierstorff Nov 21 '17 at 16:07
  • @EikePierstorff solution you posted executes javascript on particular element, in my case I just want to execute in stand alone mode to fetch value out of it – vikramvi Nov 21 '17 at 16:17
  • No, not really. In Python I can do driver.execute_script("return window.dataLayer") and that will return the JSON from the dataLayer as a dict. As I understand the question that I have linked this should work similiarly in Java. – Eike Pierstorff Nov 21 '17 at 16:22
  • @EikePierstorff Thanks for your pointers. I could get it working as below ArrayList myList = new ArrayList(); myList = (ArrayList) js.executeScript("return window.dataLayer"); Now next challenge is to extract data in optimized way as has got key-value pairs with some each key having different number of values – vikramvi Nov 21 '17 at 17:07

1 Answers1

2

I could achieve with below code

        JavascriptExecutor js = (JavascriptExecutor)getDriver();

        ArrayList<Map<String, List<String> >> myList = new ArrayList<>();

        //Execute GTM script to fetch values       
        myList =  (ArrayList) js.executeScript("return window.dataLayer");

        // Parse through GTM arrayList  
        for(int a=0; a < myList.size(); a++) {
            for (String key : myList.get(a).keySet()) {
                System.out.println(key + "      " + myList.get(a).get(key));

            }
        }

         //Next Step
         // assert against expected values
vikramvi
  • 3,312
  • 10
  • 45
  • 68