Valip
Valip

Reputation: 4620

How to execute a javascript code in puppeteer

I'm new to puppeteer and trying to figure out how to execute a javascript code, provided as a string value, in puppeteer.

For example, the value (which is retrieved from an input) can look like this: document.getElementById('selector').value='some_value';

I've implemented the following code

const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://www.southwest.com/', { waitUntil: 'domcontentloaded' });
const script = await page.evaluate("document.getElementById('LandingAirBookingSearchForm_originationAirportCode').value='Dallas'; document.getElementById('LandingAirBookingSearchForm_originationAirportCode').dispatchEvent(new Event('input',{bubbles:!0}));");
await browser.close();

But it returns the following error:

Evaluation failed: TypeError: Cannot set property 'value' of null

Upvotes: 4

Views: 14756

Answers (1)

Mischa
Mischa

Reputation: 1601

  1. Evaluate your script on the page in a callback
  2. Wait for the element with the ID of 'LandingAirBookingSearchForm_originationAirportCode' before you execute the script to be sure the side has loaded
const puppeteer = require('puppeteer');

(async function () {
    const browser = await puppeteer.launch(/*{headless: false}*/);
    const page = await browser.newPage();
    await page.goto('https://www.southwest.com/', { waitUntil: 'domcontentloaded' });
    await page.waitFor('#LandingAirBookingSearchForm_originationAirportCode');
    await page.evaluate(() => {
        document.getElementById('LandingAirBookingSearchForm_originationAirportCode').value='Dallas'; 
        document.getElementById('LandingAirBookingSearchForm_originationAirportCode').dispatchEvent(new Event('input',{bubbles:!0}));
    });
    await browser.close();
})();

Upvotes: 4

Related Questions