Practical Tricks for Working With Playwright

When you work with Playwright, there are a few small things that you want to change. Often there is a flag for codegen or a settings value that will do the trick. I collected the customisations for the parts I find most useful. Feel free to add a comment for other tricks you think I should know about.

The customisations go in 3 basic places: The command line for changes to codegen, the BrowserTypeLaunchOptions() when we launch the browser or the context that we get from the newly created browser. If you get stuck, you best use the codegen option and then look at the generated code to copy that into your application. That works across languages and frameworks.

 

Run outside the headless mode

We can leave the headless mode for dotnet test by setting this environment variable:

Or we can call the LaunchAsync() method with this BrowserTypeLaunchOptions() settings where we change Headless to false:

 

Change the language

We can change the language that the browser in codegen accepts with the --lang option:

In our code we must set the Locale property on the context:

 

Change the browser

We can change the browser we use in codegen with the --browser option and change it from chromium to firefox or webkit:

In our code we can chose the browser explicitly:

 

Run in full screen

There is an open issue for a solution to open the browser in full screen. However, I got everything I needed with this code from Stack Overflow:

This adds an argument to the BrowserTypeLaunchOptions() and it changes the ViewportSize to NoViewport.

 

Use a specific viewport

We can get a specific viewport in codegen with the --viewport-size option:

In our code we can set the viewport size in the context:

If we only need a different viewport for a specific page, we can do that as well:

 

Change user agent

We can change the user agent in the context object with this code:

 

Emulate devices

Playwright allows us to emulate devices. The emulation covers the viewport size, the user agent, if it is a mobile device, and if it supports touch. You can find the list of pre-defined devices and their names here on GitHub.

For codegen, we can use the --device option:

In the code we can get the device configuration and use it to create a new context:

 

Simulate geolocation

We can emulate the location of the browser with the --geolocation option for codegen:

Or we can set the location on the context:

 

Next

While not necessary, those tricks may help you to get from Playwright exactly what you need. While you maybe never need to set the geolocation, it is good to know that you could do it. Next week we try to run Playwright on BrowserStack to see if we could switch away from Selenium without losing the real device emulations we can get with this service.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.