How to wait for jquery to be loaded after await page.addScriptTag({url: ‘https://code.jquery.com/jquery-3.2.1.min.js’}) in Puppeteer?

Tags: , , ,



CODE:

await page.addScriptTag({url: 'https://code.jquery.com/jquery-3.2.1.min.js'});

PROBLEM:

I add jquery to the page with the line above so that I can use it to select elements in Puppeteer. Everything works fine for a few pages, until the error “$ is not defined” appears.

Edit: To be clear, the first url is loaded and then puppeteer navigates by clicking the “next” button to go to the next page, thus opening a new page at a new url.


WHAT I TRIED:

I have tried the following:

1)

 await page.evaluateOnNewDocument(fs.readFileSync('./public/js/jquery.js', 'utf8'));

2)

page.on('framenavigated', async frame => {
                    if (frame !== page.mainFrame()) { return; } 
                    else {
                        await page.addScriptTag({path: './public/js/jquery.js'});
                    }
            })

3)

 await page.addScriptTag({url: 'https://code.jquery.com/jquery-3.2.1.min.js'});

Nothing works. What would you suggest ?

Answer

You can use waitForFunction,

await page.addScriptTag({url: 'https://code.jquery.com/jquery-3.2.1.min.js'});
await page.waitForFunction(() => window.jQuery);

It will wait until the windows has a jQuery variable and resolve when it does.



Source: stackoverflow