It's important to note that a frame
object remains consistent across all event callbacks it is passed to. To identify which frame is being referenced in a specific callback, you can utilize the strict equality operator ===
.
For instance, consider this scenario where a frame is added to an array and then removed using ===
for comparison, resulting in the array's length going back to 0:
const playwright = require("playwright"); // ^1.39.0
const html = `<!DOCTYPE html><html><body>
<iframe src="https://www.example.com"></iframe>
</body></html>`;
let browser;
(async () => {
browser = await playwright.firefox.launch();
const page = await browser.newPage();
let frames = [];
page.on("frameattached", frame => {
frames.push(frame);
console.log(frames.length); // => 1
});
page.on("framedetached", frame => {
frames = frames.filter(e => e !== frame);
console.log(frames.length); // => 0
});
await page.setContent(html);
await page.$eval("iframe", el => el.remove());
})()
.catch(err => console.error(err))
.finally(() => browser?.close());
Feel free to play around with this code and add more frames--you'll observe that the array consistently ends up empty, provided all added frames are removed.
If needed, you can employ alternative methods to identify frames, such as their source URLs, tailored to your application's requirements. In most situations, direct frame management is unnecessary. If you encounter challenges implementing this, consider providing additional context on your goals, as there may be more suitable approaches available.