Why is the on click event on anchor not triggering while manually clicking in a debug session from VS Code?
Broadly here is my goal:
In code, this is what I got
const puppeteer = require('puppeteer')
async function main() {
const browser = await puppeteer.launch({ headless: false })
const page = await browser.newPage();
await page.goto('https://www.linkedin.com/');
await login(page);
await page.goto('https://www.linkedin.com/jobs/');
await attachLinks(page);
await page.screenshot({ path: "bla" })
browser.close();
};
async function attachLinks(page) {
const bodyHandle = await page.$('body');
await page.evaluate( (body, numLinks=3) => {
let anchors = Array.from( body.querySelectorAll("a") ).
filter( (e, i) => i < numLinks );
for(let i = 0; i < anchors.length; i++) {
let a = anchors[i];
console.log(`Binding for ${a.href}`);
// This event does not trigger!!!!!
a.addEventListener("click", e => {
console.log("some one clicked the link");
e.preventDefault();
e.stopPropagation();
return false;
});
};
}, bodyHandle);
await bodyHandle.dispose();
}
main();
Then using VS Code and node.js debugging support, I put a breakpoint on line await page.screenshot({ path: "bla" })
after the onclick
event for <a>
tags is attached. In the browser that opens (as headless is set to false), while the code is waiting to be resumed, I clicked the <a>
tags in the <body>
with my mouse, expecting to see "some one clicked the link" in the headful debug Chrome browser's console. But I dont see a logs either in the browser or in VS Code's Debug console. Am I missing something here?
That's because you are not actually clicking the anchor tag. You've attached an event to it "click" and defined what will happen when we will click it, but you're not actually clicking it. Just add a.click()
like
// This event will now trigger
a.addEventListener("click", e => {
console.log("some one clicked the link");
e.preventDefault();
e.stopPropagation();
return false;
});
a.click();
see the name addEventListener
, you're attaching an event listener, not actually clicking it
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.