Skip to content
Advertisement

Playwright Select frame with dynamic name

I need to access an iframe in playwright that has a name that is automatically generated.

The iframe’s name is always prefixed by “__privateStripeFrame” and then a randomly generated number

How i can access the frame with the page.frame({name: }) ?

From the docs it seems like i can’t use a regular expression!

Advertisement

Answer

The frameSelector doesn’t need be specified by the name. Try an xpath with contains – this works on the W3 sample page:

    await page.goto('https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_iframe');
    await page.frame("//iframe[contains(@title,'W3s')]");

If you want a more general approach – you also have page.frames(). That will return an array of the frames and you can iterate through and find the one you need.

This works for me:

    let myFrames = page.frames();
    console.log("#frames: " + myFrames.length)
    myFrames.map((f) => console.log(f.name()));

frames on w3c

(W3S is not the best demo site as there are lots of nested frames – but this outputs the top level frames that have names)

The output:

iframeResult

__tcfapiLocator

__uspapiLocator

__tcfapiLocator

__uspapiLocator

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement