Show hidden characters
Up until now, we’ve seen scenarios where Playwright can directly or indirectly pierce the shadow root. Now if the element is inside a closed shadow root, how do we enter that element? There is a separate school of thought or approach as to why even automate that? I kind of agree to that, but any how let’s test if we can use any kind of workaround to get text to that element.
import { chromium,test } from "@playwright/test";
test.use({ viewport: { width: 1400, height: 1000 } });
test('Launch the Selectors hub test page',async()=>{
const browser = await chromium.launch({
headless: false
const context = await browser.newContext();
const page = await context.newPage();
await page.goto("https://selectorshub.com/xpath-practice-page/");
await page.waitForSelector('.dropbtn',{
state: "visible"
await page.locator('div#userPass').click();
await page.keyboard.press('Tab');
await page.evaluate(() => document.activeElement.setAttribute('value','Top Gun Maverick'));
await page.keyboard.press('Enter');
await page.waitForTimeout(5000);
The code runs successfully, without any failure but the input box doesn’t show the value. Hmm. Let’s see if the value is being set correctly.
Add this piece of code
let textcontent = await page.evaluate(()=> document.activeElement.getAttribute('value'));
await console.log(`The value set is ${textcontent}`);
This gives a console output which shows that value is set
await page.locator("#userName input#pizza").click();
await page.keyboard.press('Tab');
await page.waitForTimeout(5000);
await page.evaluate(() => document.activeElement.setAttribute('value','hawke'));
const pagetext = await page.evaluate(() => document.activeElement.getAttribute('value'));
await console.log(pagetext);
In this case also the
value
attribute is set but the value doesn’t show up on the UI, which means that in Scenario 4, the type of input field which is
password
doesn’t make any difference. I’ll track this in the github issue mentioned above and let’s see what transpires.
Edit 1
: I got a response on my question above and the solution is pretty simple. We can use the
type
command to sent the text input. So essentially we modified our code to this
await page.locator("#userName input#pizza").click();
await page.keyboard.press('Tab');
await page.keyboard.type('I love pizza');
await page.waitForTimeout(5000);
In the above 5 scenarios, we saw how Playwright makes it easy to interact with Shadow DOM elements. For the closed ones, I’ll try to work to see if there can be any other work around, which I think should be possible, given the power of JS. In the next blog, maybe we’ll have a look at how we can work with different scenarios in iframes.