Getting url from webpage

hi. i wrote a simple script thas is supposed to acomplish the following task:

  1. open a bowser in a url that was recevied in the command line
  2. wait until the value of the address bar changes
  3. write the new address bar value to a file
  4. close the browser.

i keep getting chrome-error://chromewebdata/ instead of the actual value (which is supposed to be localhost with some code that is generated, and nothing presented on screen.)

anyone know why is this behevior is happning?

code added for reference.

const puppeteer = require('puppeteer');
const fs = require('fs');

(async () => {
  // Get the initial URL from the command line arguments
  const initialUrl = process.argv[2];
  if (!initialUrl) {
    console.error('Usage: node script.js <URL>');
    process.exit(1);
  }

  // Launch the browser
  const browser = await puppeteer.launch({headless: false});
  const page = await browser.newPage();

  // Go to the initial URL
  await page.goto(initialUrl, {waitUntil: 'networkidle2'});

  // Listen for the 'framenavigated' event
  page.on('framenavigated', frame => {
    if (frame === page.mainFrame()) {
      const newUrl = frame.url();
      if (newUrl !== initialUrl) {
        // Write the new URL to a file and close the browser
        fs.writeFileSync('newUrl.txt', newUrl);
        console.log(`New URL (${newUrl}) saved to newUrl.txt`);
        browser.close();
      }
    }
  });
})();

What happens if you attach the listener before awaiting goto?

Hi @goodybh,

Welcome to the forum.

Just to let you know, you can format your code in the text editor by selecting the code and clicking on the </> menu item at the top. This will enclose the code text in three opening and closing ticks ```.

I have done it for you this time.

Thank you.

thank you, i will format in this way going forward.

1 Like

hi i got Error: Navigating frame was detached.
when i changed it to dont consider the first url as a change it gave me the same answer in the file. i dont think this is the problem because i can see the correct value in the adress bar but it does not being written to the file.

I also have this error, it keeps happening, but it only happens when I put the url in the img tag. Iā€™m not sure if you have fixed this error yet?