Add jQuery to a Puppeteer-controlled webpage

I’m having trouble adding jQuery to a page I’m controlling with Puppeteer. The document.querySelector method isn’t enough for what I need to do. Here’s what I’ve tried:

async function addJQueryToPage(page) {
  await page.evaluate(() => {
    let script = document.createElement('script');
    script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js';
    document.head.appendChild(script);
  });
  await page.waitForFunction('typeof jQuery !== "undefined"');
}

But it usually times out. Does anyone know a better way to do this? I’m not sure if I’m doing something wrong or if there’s a different approach I should be using. Any help would be great!

I’ve been working with Puppeteer for a while now, and I’ve found that using CDP (Chrome DevTools Protocol) is a more robust way to inject jQuery. Here’s what I typically do:

await page.evaluateOnNewDocument(() => {
  window.addEventListener('load', () => {
    const script = document.createElement('script');
    script.src = 'https://code.jquery.com/jquery-3.6.0.min.js';
    document.body.appendChild(script);
  });
});

This approach ensures that jQuery is loaded after the DOM is ready, which has been more reliable in my experience. It also doesn’t block the page load, which can be crucial for performance.

One thing to keep in mind: make sure you’re waiting for jQuery to be fully loaded before trying to use it in your Puppeteer scripts. You can do this by checking for the jQuery object’s existence before proceeding with your operations.

hey mate, i’ve faced similar issues. instead of waiting for jQuery, try this:

await page.evaluateOnNewDocument(() => {
const script = document.createElement(‘script’);
script.src = ‘https://code.jquery.com/jquery-3.6.0.min.js’;
document.head.appendChild(script);
});

This injects jQuery before page load. should work better!

I’ve encountered this issue before, and I found a more reliable solution. Instead of injecting jQuery dynamically, you can use Puppeteer’s setContent method to add jQuery directly to the page’s HTML. Here’s an approach that worked for me:

await page.setContent(`
  <html>
    <head>
      <script src='https://code.jquery.com/jquery-3.6.0.min.js'></script>
    </head>
    <body>
      ${await page.content()}
    </body>
  </html>
`);

This method ensures jQuery is loaded before any other content, avoiding race conditions. It’s been consistently effective in my projects. Just make sure to call this function after navigating to your target page but before performing any jQuery-dependent operations.