Playwright Tutorial: IFrame and Shadow DOM Automation

Introduction

In this post, we will go through the basics of IFrames and Shadow DOM, and we will learn the strategies of automating these complex HTML structures with Playwright.

Most often, when doing automated tests, we will deal with standard elements like divs, buttons, anchors, input fields, etc. Furthermore, we can navigate through the DOM tree by CSS or XPath with extra steps. However, some pages may have more complex elements and the two of them that we will review are:

  • IFrame (inline frames)
  • Shadow DOM

In general, they have a very specific reason to be used; IFrames embed external HTML, while Shadow DOM encapsulates a DOM tree so that no external CSS or JavaScript can alter the content inside. As you might have guessed by their nature, they alter our interaction with the page’s content and make the navigation inside the DOM tree slightly more complex.

What are IFrames?

An iframe (short for “inline frame”) is an HTML element that allows you to embed another HTML document within a webpage. It functions as a “window” that can display a separate HTML page or content from a different source, such as an external website or service, without fully integrating it into the main HTML structure.

Above all, this allows content separation and provides a way to embed external resources without fully merging code. On the other hand, they also have some identified risks which include: security vulnerabilities, complicated responsiveness, or simply be not SEO-friendly since search engines might not index iframe content on the parent page.

Common Uses

Embedding a Youtube Video

This allows you to play the video without hosting it directly. This is ideal for blogs, news sites, etc.

Youtube Video Embedded in the Page with IFrame

Displaying Google Maps

This allows the users to view a location without leaving the website, which is useful for contact or location pages where the visitors can see the address on a map and also zoom in and out or simply using navigation features.

Google Maps Embedded in the Page with IFrame

Social Media Plugins (e.g., Facebook, Twitter)

Some social platforms provide iframes for integrating feeds or buttons directly on your website. Embedding posts or feeds from platforms like Facebook or Twitter enables users to view them directly in the site, without leaving.

Ads and Sponsored Content

Iframes are commonly used for loading advertisements since they keep the ad content separate from the main content of the website. Ad networks often deliver ads in iframes to isolate their scripts and styles from the host page, improving security and ensuring ad content doesn’t interfere with site content.

Automating IFrames With Playwright

When working with Playwright, we encounter the need to interact with iframes or elements inside them, we can create a frame locator that will point to the iframe and will allow selecting elements in it.

IFrame Sample
try (Playwright playwright = Playwright.create()) {     Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));     Page page = browser.newPage();      page.navigate(URL);      FrameLocator iframe = page.frameLocator("iframe");     Locator contactUsButton = iframe.locator("//div[@class='section-content']//a[@class='button']");     contactUsButton.click(); } 

This method returns an object of type FrameLocator, which represents the iframe element on the page. It only has logic sufficient to retrieve the iframe and locate elements further inside, which will be again normal Locator objects. However, if we need to execute more complex logic against the iframe element itself and we have only a FrameLocator for it, we can simply use the owner() method, which will return a Locator object that will point to the same iframe. Furthermore, the reverse is also true – If we have a Locator object pointing to an iframe and we want to enter it, we can use the method contentFrame(), which will return FrameLocator and we could continue locating elements further inside.

FrameLocator iframe = page.frameLocator("iframe");  Locator iframeElement = iframe.owner(); assertThat(iframeElement).hasClass("important"); 
Locator iframeElement = page.locator("iframe");  FrameLocator iframe = iframeElement.contentFrame(); Locator contactUsButton = iframe.locator("//div[@class='section-content']//a[@class='button']"); 

Locating works the same way for both Locator and FrameLocator objects and you can see further information about different locating tactics here.

What is Shadow DOM

The Shadow DOM is a web standard that allows developers to encapsulate a part of the DOM (Document Object Model) so that it is isolated from the rest of the document. This helps in creating reusable components with their own internal structure, style, and behavior, without affecting the global scope of the page or being affected by external styles and scripts.

How it Works?

<div id="host">This is the shadow host</div>  <script>   // Create a shadow root attached to the div with id 'host'   const host = document.getElementById('host');   const shadowRoot = host.attachShadow({mode: 'open'}); // 'open' allows access to the shadow DOM from JavaScript    // Add content to the shadow DOM   shadowRoot.innerHTML = ` 	<style>   	p {     	color: red;   	} 	</style> 	<p>This is inside the Shadow DOM!</p>   `; </script> 

An element acts as the shadow host and through JavaScript we ‘attach’ a shadow root to it. As we can see here, the method attachShadow takes one parameter and that is ‘mode’.

The mode parameter has two values; ‘open’, which makes the shadow DOM accessible via JavaScript (using host.shadowRoot); and ‘closed’ which makes the shadow DOM inaccessible via JavaScript. This means that the ‘shadowRoot’ property of the host element will be null, preventing access to the shadow DOM from external scripts. This is done to prevent external manipulation and to ensure complete encapsulation of the shadow tree, making it more secure and private.

No matter the mode, the shadow DOM will be visible in the DevTools Inspector.

Common Uses

Encapsulated Widgets

Shadow DOM allows third-party developers to create widgets or embedded components that function independently of the main page’s styles and scripts. This is particularly useful when you’re embedding external content like advertisements, interactive elements, or even complex embedded widgets.

Reusable UI Components

Using the Shadow DOM, developers can build reusable UI components (like buttons, sliders, tooltips, or form fields) that are completely self-contained. These components can be reused across different projects or pages without worrying about conflicting CSS or JavaScript.

Automating Shadow DOM With Playwright

Automating the shadow DOM with Playwright is much more straightforward than iframes, as you will see below.

Shadow Dom Example
try (Playwright playwright = Playwright.create()) {     Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));     Page page = browser.newPage();      page.navigate(URL);      Locator shadowDomButton = page.locator("#rick-roll");     shadowDomButton.click();      assertThat(page.locator("iframe")).hasAttribute("src", "https://www.youtube.com/embed/dQw4w9WgXcQ?si=KBslwFMURU4s2km8"); } 

Playwright pierces the shadow DOM seamlessly if we are locating with CSS. As a result, we can locate any element wherever its location in the DOM tree, as long as we are using CSS locator strategy or Playwright strategies based on CSS.

However, if we need to find an element, for example, through its inner text, which we cannot get as a value with CSS, we would technically need XPath. That is impossible for elements inside the shadow DOM. Another example would be if we need to find an element relative to another element, like ancestor-descendent relation. That is, for example, finding an element by the criteria that it contains another specified element.

Although most of the cases could easily be covered with CSS locators alone, in some cases that is not feasible. Nevertheless, a solution could be made and we could use it to find elements by XPath in the shadow DOM. More information about XPath usage for shadow DOM is available here.

Summary

This Playwright tutorial covers how to automate complex HTML structures like IFrames and Shadow DOM in web testing. Playwright simplifies interacting with IFrames – which are used to embed external content such as videos, maps, ads, etc. – using FrameLocator objects for element selection and manipulation. The tutorial also explains Shadow DOM, a technique that encapsulates content to avoid external interference, and demonstrates how to automate it using Playwright’s CSS locator strategy. Finally, the post discusses how to handle scenarios involving both IFrames and Shadow DOM, ensuring efficient and reliable test automation.

For more information we highly recommend visiting the official Playwright documentation.

The post Playwright Tutorial: IFrame and Shadow DOM Automation appeared first on Automate The Planet.

Automate The Planet

Author: admin

Leave a Reply

Your email address will not be published. Required fields are marked *