Examples: Use Google Analytics in LWR Sites
In each example, you add the provided code sample to the head markup. To access the head markup in your LWR site, in Experience Builder click
.Because you’re adding Google Analytics as a third-party library, switch to Relaxed CSP in Experience Builder in
. Also add the URL for your Google Analytics script to the Trusted Sites for Scripts list on this page.Example 1: Track Page Views
This example tracks when a user views a page in an LWR site. In the sample code, the pushstate event is fired when a visitor lands on a site page. The event listener on the window passes the event to Google Analytics along with the page URL.
Example 2: Track Click Events
In this scenario, a page in the LWR site contains a button called Submit and a link called Download. Google Analytics can track when a customer clicks the button or the link.
In the sample code, the buttonAndLinkClick function uses the .button_class class to listen for a click event on the Submit button. The function also uses .download_link to listen for a click event on the Download link. When either event is fired, the event listeners on the button and link pass the event details to Google Analytics under the link_button_click event category.
Example 3: Track Form Input and Submissions
In this scenario, a page in the LWR site contains a form called Subscribe, and within the form, a button called Submit. Google Analytics can track when a user enters information in the form or clicks Submit.
In the sample code, the formClick function uses the .subscription_form_class class to listen for a change event on the form input fields and a click event on the Submit button. When either event is fired, the event listener on the form passes the event details to Google Analytics under the input_change event category or the form_submit_success event category.
Example 4: Track Outbound Link Clicks
In this scenario, a page in the LWR site contains links that redirect users to external websites. Google Analytics can track when a user clicks any of these outbound links.
In the sample code, the trackOutboundLinks function uses the .outbound class to listen for a click event on an external link. When a click event is fired, the event listener on the link passes the event details—including the external redirect link—to Google Analytics under the outbound event category.
Example 5: Track Visit Duration
In this scenario, Google Analytics tracks how long a user stays on a page on the LWR site.
In the sample code, the beforeunload event listens for a page refresh or page unload. The window.performance attribute from the global window object measures the time since the user landed on the page. When the beforeunload event is fired, the event listener on the window passes the event details to Google Analytics, including the duration of the user’s stay on the page.