25

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

emery
  • 8,603
  • 10
  • 44
  • 51
gabogabans
  • 3,035
  • 5
  • 33
  • 81
  • 1
    I re-wrote the original question for clarity and nominated this for re-opening again, as this was the correct and easy-to-google answer for the question I needed. – emery Oct 19 '22 at 20:27

2 Answers2

21

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
15

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();
}
emery
  • 8,603
  • 10
  • 44
  • 51