Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject jQuery into Puppeteer page

I'm trying to inject jQuery into my Puppeteer page because document.querySelector doesn't cut it for me:

async function inject_jquery(page){   await page.evaluate(() => {     var jq = document.createElement("script")     jq.src = "https://code.jquery.com/jquery-3.2.1.min.js"     document.querySelector("head").appendChild(jq)   })   const watchDog = page.waitForFunction('window.jQuery !== undefined');   await watchDog; } 

The result is it mostly times out. Does anyone have a solution?

like image 649
pguardiario Avatar asked Oct 28 '17 07:10

pguardiario


People also ask

Can I use jquery in puppeteer?

UPDATE: I tried a small snippet to test jquery. The puppeteer version is 10.4. 0. So the jquery code is definitely working.

What does Page Evaluate do in puppeteer?

Evaluates a function in the page's context and returns the result. If the function passed to page. evaluteHandle returns a Promise, the function will wait for the promise to resolve and return its value.

What is Page on in puppeteer?

The Puppeteer page class extends Node. js's native EventEmitter , which means that whenever you call page. on() , you are setting up an event listener using Node.


2 Answers

I have used page.addScriptTag to inject js files.

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

page.addScriptTag - documentation

Working example using puppeteer: 0.12.0

import { launch } from 'puppeteer' (async () => {     const browser = await launch({headless: false});     const page = await browser.newPage();     await page.goto('https://example.com', {waitUntil: 'networkidle'});     await page.addScriptTag({url: 'https://code.jquery.com/jquery-3.2.1.min.js'});     await page.close();     await browser.close(); })(); 
like image 50
nilobarp Avatar answered Oct 14 '22 13:10

nilobarp


For those looking to inject a local copy of jQuery:

await page.addScriptTag({path: require.resolve('jquery')})

like image 22
subeebot Avatar answered Oct 14 '22 14:10

subeebot