Monday, May 19, 2025

How to update a partial URL in playwright

In this example we will explore how to update partial URL in playwright. To update a partial URL in Playwright, you can use page.goto() with the new URL. If you need to wait for the updated URL to be fully loaded, use page.waitForURL(). You can also use the URL() constructor to transform relative URLs into absolute URLs for consistency. 

How to update a partial URL in playwright


Steps:

  1. Get the current URL: Use page.url() to retrieve the current page's URL. 
  2. Create the new URL: Combine the current base URL (if you have one) with the partial URL update you want to make. You can use the URL() constructor to help with this, especially if dealing with relative URLs. 
  3. Navigate to the new URL: Use page.goto() with the newly constructed URL. 
  4. Wait for the new URL to load (optional): If you need to ensure the page has fully loaded after the URL update, use page.waitForURL() with the expected new URL. 


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

(async () => {
  const browser = await chromium.launch({ headless: false });
  const context = await browser.newContext();
  const page = await context.newPage();

  // Navigate to a base URL
  await page.goto('https://example.com');

  // Get the current URL (optional)
  const currentURL = page.url();

  // Create the new URL (partial update)
  const newURL = new URL('/new-path', currentURL).href;

  // Navigate to the new URL
  await page.goto(newURL);

  // Wait for the URL to update (optional)
  await page.waitForURL('https://example.com/new-path');

  console.log('Page navigated to:', page.url());

  await browser.close();
})();


This is all about updating a partial URL in playwright.


No comments:

Post a Comment