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 ?

6
  • 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. Commented Nov 21, 2017 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 Commented Nov 21, 2017 at 15:53
  • 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. Commented Nov 21, 2017 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 Commented Nov 21, 2017 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. Commented Nov 21, 2017 at 16:22

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.