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.