In selenium there is a method switchTo
that can be used to switch to a frame.
Is there anything similar in Playwright?
driver
vs Playwright page
Tl:dr - Driving the browser and everything inside it vs interacting with the browser and specific tabs (or “pages”) within it
Not exactly. Playwright takes a slightly different approach. Instead of just a driver
which contains all the methods to drive the browser and anything within it, Playwright splits this into more specific pieces - browser
, context
, and page
.
Browser is for the browser itself as a whole, which can contain many contexts and tabs.
BrowserContext for specific independent browsing sessions (for instance, a tab opened by another tab will be part of the same session or context).
Page for controlling a specific tab (or “page”) within the browser/context. Each separate tab will have its own Page instance to represent it.
The benefits of this include being able to share context between pages, working with multiple tabs simultaneously more easily, and other areas where the separation is useful. You’re not tied down to just using one driver instance for everything.
For your question there’s an added piece, Frames, which you can access directly from a Page still, while also allowing you to interact with it separately/as its own entity or “page” in a way. The main page is really just its own top frame with page content, and each iframe is basically its own page with its own content.
The closest thing to switchTo here would be to just use .frame()
to get the specific Frame and interact with it, whether by calling .frame each time or just storing, using, and passing around the frame itself. It has most of the main methods of Page you would use/need anyway, so in many cases can just be used in its place. So while not exactly like switchTo in making the page interact with the other frame (or tab) and having to switch back, because that was actually telling the driver to drive one vs the other, you can just access the Frame itself to interact with for those parts, and keep the page representing the full page.
Note that there is a difference between FrameLocator and Frame. The first solely provides a way to locate elements within an iframe, whereas the second is like another Page specific to that frame allowing you to interact with it similarly.