Search code examples
javascriptpuppeteerheadless

UnhandledPromiseRejectionWarning: ReferenceError: browser is not defined for azure login with puppeteer


I am trying to automate my application which is running on azure portal using puppeteer. And I am getting following error after entering the password it is not clicking the submit button.

node:55768) UnhandledPromiseRejectionWarning: ReferenceError: browser is not defined

Here is my sample code:

(async () => {
  
  try {
    const launchOptions = { headless: false, args: ['--start-maximized'] };
    const browser = await puppeteer.launch(launchOptions);
    const page = await browser.newPage();
    await page.emulate(iPhonex);
    await page.goto('https://apps.testpowerapps.com/play/72ff5b93-2327-404d-9423-92eedb44a287?tenantId=n082027');
     
      //Enter User Name
      const [userName] = await page.$x('//*[@id="i0116"]');
      await userName.type("jyoti.m@azure.com");
        const [loginButton] = await page.$x('//*[@id="idSIButton9"]');
        await loginButton.press('Enter');
   
       //Enter Password
      const [passWord] = await page.$x('//*[@id="i0118"]');
      await passWord.type("Pass123");
        
        const [submitButton] = await page.$x('//*[@id="idSIButton9"]');
        await submitButton.press('Enter');
        //await page.keyboard.press('Enter');

  }
  catch(error){
  console.error(error);
  }
  finally {
    await browser.close();
  }
})();

Tried with both way but not working only catch is the xpath for both the pages are same.

 const [submitButton] = await page.$x('//*[@id="idSIButton9"]');
    await submitButton.press('Enter');
    //await page.keyboard.press('Enter');

any clue to resolve this.


Solution

  • You define the browser value in the try but you also use it in the catch. consts are block-scoped, so they are tied to the block, so a different block (the finally) can not see it.

    Here is the problem:

      try {
        const browser = ...;
      }
      finally {
        // different block!
        await browser.close();
      }
    

    To solve this, move the browser out of the try-catch:

      const browser = ...
      try {
    
      }
      finally {
        await browser.close();
      }
    

    This way it's available in the finally block.