Playwright get current url

    
      const { chromium } = require('playwright'); // Importing 'chromium' module from 'playwright'
      
      (async () => { // Defining the async function
      
          const browser = await chromium.launch(); // Launching the chromium browser
          const context = await browser.newContext(); // Creating a new browser context
          const page = await context.newPage(); // Opening a new page in the browser context
      
          await page.goto('https://example.com'); // Navigating to 'https://example.com' URL
      
          const currentURL = page.url(); // Getting the current URL of the page
          console.log('Current URL:', currentURL); // Logging the current URL
      
          await browser.close(); // Closing the browser
      
      })();
      
    
  

The above code snippet demonstrates how to use Playwright to get the current URL of a page and display it using JavaScript.

In order to run this code, you need to have Playwright installed and import the ‘chromium’ module from Playwright. The code also assumes that you are working with Node.js.

Explanation of the code:

1. We start by importing the ‘chromium’ module from Playwright, which allows us to work with the Chromium browser.

2. Inside an async function, we launch a new instance of the Chromium browser using `chromium.launch()` function.

3. We create a new context using `browser.newContext()`.

4. Then, we open a new page within the context using `context.newPage()`.

5. Using `page.goto()`, we navigate to a specific URL, in this case, ‘https://example.com’.

6. To get the current URL of the page, we call `page.url()` and assign the result to the ‘currentURL’ variable.

7. Finally, we log the current URL by using `console.log()`.

8. After performing the necessary actions, we close the browser and terminate the script execution by calling `browser.close()`.

This code snippet can be modified to work with different URLs. You can replace ‘https://example.com’ with the desired URL that you want to get the current URL for.

Leave a comment