Using Geolocation in Playwright tests

Tim Deschryver

In this blog post, we go over the basics of how to use the Geolocation API with Playwright.

You might have already written some code to get access to the user's location. Even if you haven't, you probably have already seen the browser asking for permission to access your location. This is not different in Playwright tests.

When your application tries to access the location during a test, the same prompt will appear.

The Playwright browser asking for permission to use the location in a test

This is blocking the test execution, and after a few seconds, it results in a timeout. Luckily we don't have to click the "Allow" button manually for every test.

Giving permission to use the location link

To get rid of the prompt, we need to configure Playwright to have permission to use the location. This is done in the Playwright config file, via the use option.

While this grants permission to the browser context to read the user's location, it doesn't actually set the location.

The permission prompt is gone, but the application doesn't receive the coordinates.

Setting the location link

We're over the first hurdle, but we still need to set the location.

Provide a global geolocation configuration link

To set the location globally, we set the geolocation option in the Playwright config file to emulate a user's location.

When we run the test now, the application receives the coordinates and the location is set.

The page showing the coordinates we set in the global config.

Stubbing the location for a specific test(s) link

To set the location for a specific test, inject the browser context in the test (context), and set the location with the setGeolocation() method.

When multiple tests need to overwrite the location, you can also set the location for all tests within a file.

Or, set the location for all tests within a describe block.

Feel free to update this blog post on GitHub, thanks in advance!

Join My Newsletter (WIP)

Join my weekly newsletter to receive my latest blog posts and bits, directly in your inbox.

Support me

I appreciate it if you would support me if have you enjoyed this post and found it useful, thank you in advance.

Buy Me a Coffee at PayPal logo

Share this post on

Twitter LinkedIn