0

Example, if I don't dispatch it, this event throws an error when I close the browser.

await page.on("response", async resp => {
  if (resp.url().includes("navigator.successRedirect")) {
    let code = await page.$eval("pre", el => el.textContent);
    code = JSON.parse(code).authorizationCode;
    console.log(code);
    // page.off('response', this) - Here I want to dispatch this event, how can I do that?
    await browser.close();
  }
});
ggorlen
  • 44,755
  • 7
  • 76
  • 106
Mirikkingg
  • 63
  • 1
  • 6

1 Answers1

1

If you store the function in a variable, you can use off:

const handleResponse = async response => {
  if (response.url().includes("navigator.successRedirect")) {
    let code = await page.$eval("pre", el => el.textContent);
    code = JSON.parse(code).authorizationCode;
    console.log(code);
    page.off("response", handleResponse);
    await browser.close();
  }
};
page.on("response", handleResponse);

However, this may be an xy problem because waitForResponse can do this without having to manually register a listener, allowing you to avoid the callback and stay in the promise chain:

await page.waitForResponse(response =>
  response.url().includes("navigator.successRedirect")
);
let code = await page.$eval("pre", el => el.textContent);
code = JSON.parse(code).authorizationCode;
console.log(code);
await browser.close();

Depending on the site, you could also wait for the <pre> element's text to change or to be nonempty, or pull the data you want out of the response, if that response has the data you want as a payload.

Note that await page.on() is misleading because on doesn't return a promise.

ggorlen
  • 44,755
  • 7
  • 76
  • 106