Get current page url with Playwright Automation tool?

52.4k Views Asked by At

How can I retrieve the current URL of the page in Playwright? Something similar to browser.getCurrentUrl() in Protractor?

4

There are 4 best solutions below

1
On

const {browser}=this.helpers.Playwright;
await browser.pages(); //list pages in the browser

//get current page
const {page}=this.helpers.Playwright;
const url=await page.url();//get the url of the current page

0
On

you can also use The page.evaluate() API

const href = await page.evaluate(() => document.location.href);

as mentioed in playwright documentation playwright evaluate API

0
On

To get and verify the current page URL using toHaveURL:

await expect(page).toHaveURL(/.*checkout/);
2
On

To get the URL of the current page as a string (no await needed):

page.url()

Where "page" is an object of the Page class. You should already have a Page object, and there are various ways to instantiate it, depending on how your framework is set up: https://playwright.dev/docs/api/class-page

It can be imported with

import Page from '@playwright/test';

or this

const { webkit } = require('playwright');

(async () => {
  const browser = await webkit.launch();
  const context = await browser.newContext();
  const page = await context.newPage();
}