Search code examples
node.jsheadless-browserplaywright

How to wait until URL change / or until connection is offline


I'm using Playwright 1.12 + Chromium 90 for daily Router restarts.
My script navigates to router's page 1.1.1.1/reset.asp
Then script click's button, accept dialog, and magic is happening inside router.
Now I have two options to have sure that router has been restarted successfully:

  1. Detect if connection in browser went "offline" (that's a good sign, I wish to wait for this event)
  2. Wait until page.url() change to 1.1.1.1 (URL in browser is changing for this one when router is UP again)

Can you give me any ideas how to achieve one of these two points?
The best would be waiting until connection in browser is offline.

Example code:

async function login() {
    // some stuff here
    await reset();
  }

async function reset() {
    // some stuff here
    // current URL is 1.1.1.1/reset.asp
    page.on('dialog', async dialog => {
      await dialog.accept();
      // I WANT TO CHANGE THIS DELAY FOR SOMETHING LIKE:
      // await waitUntilConnectionGoesDown()
      await delay(5000);
      await finish(true);
    });
    await frame.click('#reboot');
    // OR HERE WAIT FOR URL CHANGE
    // await waitForUrlChange()
    // await finish(true);
  }

  async function finish(success) {
    // success ? CLOSING BROWSER : DOING SOMETHING ELSE;
  }

Solution

  • Playwright recently has added waitForURL which you can use with a big timeout in your case to wait for the URL to navigate to your new expected URL.

    Also I would recommend to use Promise.all for your click/popup logic, see here for more information about it because then your flow is not nested inside emitted events.