Example - Use Google Tags in LWS Trusted Mode

Trusted mode lets you use gtag.js in a Lightning web component. Normally, LWS blocks gtag.js because it accesses the global window object.

gtag.js is a JavaScript tagging framework that allows you to send data from your site to Google measurement products such as Google Analytics.

This example assumes that you’re familiar with Google tags and have your gtag.js file configured with your tag ID. For more information about Google tags, see https://developers.google.com/tag-platform/gtagjs.

The gtag.js content looks similar to this code.

In a test org, follow the steps in Set Up an Org to Elevate Scripts in Trusted Mode to enable gtag to run in trusted mode. Here’s a summary of the steps.

  • Create a gtag static resource in Setup and upload your gtag.js file to it.
  • Enable trusted mode.
  • Add the gtag static resource as a trusted resource.

Here‘s the example gtag.js. Use your own tag ID instead of G-LQSDRKXXXX.

The component can load the content of each <script> tag from the resource.

Create this testTrustedMode LWC component.

testTrustedMode.html

The component template file testTrustedMode.html creates a button that calls the component’s pushed() function whenever you click the button. Clicking causes the button to send push events to Google Analytics.

testTrustedMode.js

The JS file testTrustedMode.js imports gtag from the static resource that’s also named gtag and configured for trusted mode.

In the renderedCallback() function, loadScript loads the scripts contained in the gtag static resource. The component loads the first script as gtag.js and the second script as script.js. The trustedMode property value is true for both scripts.

The trustedGlobals property allows the component to access gtag in the LWS sandbox to fire events.

When the page loads, gtag sends an event called component_loaded to Google Analytics. A pushed() function sends a gtag event called push.

testTrustedMode.js-meta.xml

The component config file testTrustedMode.js-meta.xml includes targets that enable you to use the component on all Lightning page types.

Deploy the component to your test org and add it to a Lightning page.

Here’s the button component in Lightning Experience.

Button component on a Lightning page

Go to your Analytics page. Confirm that the component loaded and the push event was triggered if you clicked the button.

Here you can see that the component loaded one time, and the button was clicked one time.

Google Analytics panel that shows one push event

In your test org, click the button several more times.

Button component on a Lightning page showing cursor

Return to your Analytics page and refresh it. Confirm that the push count increased.

Google Analytics panel that shows eight push events

This increased push count confirms that the gtag code is running outside the LWS sandbox and successfully sending events to Google Analytics.

See Also