Puppeteer监听自定义事件失败及官方示例无法正常运行的问题求助
I’ve run into nearly identical problems with Puppeteer custom event handling before, so here are some actionable fixes and checks you can try:
1. Fix Dependency Version Mismatches
The main Puppeteer repo’s examples might rely on unreleased or specific version behavior that gets broken when using a generic npm install. Instead:
- Run
npm ciinstead ofnpm installin the cloned Puppeteer repo. This uses the exact dependency versions from the repo’spackage-lock.jsonto avoid compatibility gaps. - Verify your installed Puppeteer version with
npm list puppeteerand cross-check it against the repo’spackage.jsonto ensure they match.
2. Adjust Event Listening Timing
Custom events often fire during page load, and if you set up listeners after page.goto(), you’ll miss them. Try attaching listeners before navigating to the page:
const browser = await puppeteer.launch({ headless: false }); const page = await browser.newPage(); // Set up listeners FIRST page.on('console', msg => console.log('PAGE LOG:', msg.text())); await page.exposeFunction('onCustomEvent', e => { console.log('Custom event fired:', e); }); await page.evaluate(() => { document.addEventListener('app-ready', e => window.onCustomEvent(e.detail)); }); // Then navigate await page.goto('https://example.com');
3. Tweak Browser Launch Parameters
Headless mode (even when set to false) or sandbox restrictions can interfere with event propagation. Add these args when launching the browser:
const browser = await puppeteer.launch({ headless: false, args: [ '--no-sandbox', '--disable-setuid-sandbox', '--disable-web-security' // Useful for testing, disable in production ] });
4. Validate Event Triggering Context
- Ensure the custom event is dispatched correctly in the target page. It should use
CustomEventand dispatch to the right element:// Example page-side code const appReadyEvent = new CustomEvent('app-ready', { detail: { status: 'loaded' } }); document.dispatchEvent(appReadyEvent); - If the event fires inside an iframe, you’ll need to attach listeners to the specific frame instead of the main page:
const frame = page.frames().find(f => f.url().includes('your-frame-url')); await frame.evaluate(() => { document.addEventListener('app-ready', e => console.log(e.detail)); });
5. GitLab CI Environment Specifics
In CI, headless: false requires a virtual display to work. Add this to your .gitlab-ci.yml to enable xvfb:
before_script: - apt-get update && apt-get install -y xvfb script: - xvfb-run node your-test-script.js
For the official custom-event.js example, after running npm ci and adjusting the listener timing, I was able to see the expected "fired" logs and app-ready event details in the console.
内容的提问来源于stack exchange,提问作者xtr33me

