Integrate Third-Party Libraries Using the Privileged Script Tag

Some components within an LWR site encapsulate their elements in shadow DOM, which prevents global interaction with those components. As a result, third-party JavaScript libraries such as Google Analytics and Google Tag Manager can have trouble querying the DOM globally on an LWR site. When programmatic access to an element within the DOM is needed, you can write scripts within an <x-oasis-script> privileged script tag. Loading third-party libraries using this privileged script tag lets those libraries bypass any shadow DOM boundaries.

Use the custom <x-oasis-script> tag in place of the standard <script> in the head markup or inline. Scripts loaded within this custom tag run inside a special iframe that’s exempt from shadow DOM and are always executed asynchronously.

<x-oasis-script> uses the same syntax as the <script> tag.

Where THIRD_PARTY_LIBRARY is a variable.

You can also use the tag to add event listeners and to import and export global variables with the imported-global-names and exported-global-names attributes. If you have custom code within the <x-oasis-script> tag, add the attribute hidden=“true” to the tag. This attribute ensures that the custom code within the tag remains hidden from site visitors while the page is loading.

For example, this code sample defines a global variable—testVar—on the outer window, which is then imported for use in the x-oasis-script window. The global variable must be imported to define it in the privileged scope.

In turn, this example exports the testVar global variable from x-oasis-script.

If you include a third-party library inline or in the head markup, remember to switch to Relaxed CSP and to allowlist the remote host.

  • Examples: Use Google Analytics in LWR Sites

    Discover how visitors engage with your LWR site by using Google Analytics to track their interactions. These real-world examples use the <x-oasis-script> privileged script tag. This tag allows Google Analytics to interact with elements within the shadow DOM and attach event handlers such as click events or form submissions.

  • Examples: Use Google Tag Manager in LWR Sites

    Use Google Tag Manager to track customer interactions with your LWR site, which is a single-page application. In these examples, the <x-oasis-script> privileged script tag lets Google Tag Manager interact with elements within the shadow DOM.

See Also