Interacting with Nested Shadow DOM in ServiceNow Workspace

amrfahmy
Tera Contributor

 

Interacting with Nested Shadow DOM in ServiceNow Workspace

Description: This article explains how to work with nested shadow DOM elements in ServiceNow Workspace. Since elements inside a shadow DOM are encapsulated and cannot be accessed directly with standard JavaScript methods, we will use the shadowRoot property to access and manipulate elements within nested shadow trees.

Problem Overview:

In ServiceNow Workspace, some UI components are encapsulated within shadow DOMs, and accessing these elements using standard DOM manipulation methods like document.getElementById() won't work. This requires a different approach where you need to access each shadow root layer to find and manipulate the inner elements.

Important Note:

This method of accessing nested shadow DOMs is not considered the best practice in terms of maintainability and performance. It's generally recommended to rely on standard methods for interacting with the UI elements whenever possible. However, in cases where shadow DOMs are used, this approach can be helpful to manipulate the elements.

Solution:

To interact with nested shadow DOM elements, we use the shadowRoot property repeatedly to traverse each shadow DOM layer. Here's how you can access an element inside multiple layers of shadow DOMs:

Example Use Case: Dynamic Title Based on User Role

For example, you can make the title of a component in the workspace dynamic, changing based on the user’s role. This can be achieved by manipulating the shadow DOM element like so:

function handler({
    api,
    event,
    helpers,
    imports
}) {
    helpers.timing.setTimeout(function() {
        const userRoles = api.context.session.user.roles;

        const titleText = userRoles.includes("admin") ? "Admin Workspace" : "User Workspace";
  
        this.document.querySelector('macroponent-f51912f4c700201072b211d4d8c26010')
            .shadowRoot
            .querySelector("sn-polaris-layout")
            .shadowRoot
            .querySelector("sn-polaris-header")
            .shadowRoot
            .querySelector(".experience-title")
            .textContent = titleText;
    });
}
        

Steps to Implement in UI Builder:

  1. UI Page: In the UI Builder, create a new page or modify an existing one where you want to display the dynamic title for example.
  2. Define Client Script: Use a client script to handle the logic for setting the title based on the user's role. The script can include the code for manipulating the shadow DOM.
  3. Trigger Changes on Page Load: add Event on body of page (Page Ready) to execute  the client script or when any user-related changes occur that might affect the title .

 

If you have any questions or suggestions, feel free to reach out!

1 REPLY 1

Fahd Zayed
Tera Contributor

Great article, thank you.