1
votes

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 ?

1
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
@EikePierstorff I did search but couldn't find Java solution to call javascript object and extract values. Please share your python solution here - vikramvi
There is a question/answer that might help here: stackoverflow.com/questions/11430773/…. In Python you can use the executeScript to pass "return <variable name>" in as a parameter and it returns the value for use in the python programm. I assume it works similar in Java. - Eike Pierstorff
@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
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

1 Answers

2
votes

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