'cannot find context with specified id undefined

I am trying to create an app that does a google image search of a random word and selects/clicks the first result image.

I am successful until the code is attempting to select the result image and it throws the following error in my terminal:

 UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection 
 id: 1): Error: Protocol error (Runtime.callFunctionOn): Cannot find 
 context with specified id undefined

Here is my code:

const pup = require('puppeteer');
const random = require('random-words');
const url = 'http://images.google.com';

(async() => {
  const browser = await pup.launch({headless: false});
  const page = await browser.newPage();

  await page.goto(url);
  const searchBar = await page.$('#lst-ib');
  await searchBar.click();
  await page.keyboard.type(`${random()}`);
  const submit = await page.$('#mKlEF');
  await submit.click();
  await page.keyboard.type(random());
  await page.keyboard.press('Enter');
  const pic = await page.evaluate(() => {
    return document.querySelectorAll('img');
  });

  pic.click();
})();


Solution 1:[1]

document.querySelectorAll('img') is not serialisable, so it returns undefined (see this issue as reference)

Please use something like: (depends on which element you want to click)

await page.$$eval('img', elements => elements[0].click());

Solution 2:[2]

This is a long dead thread but if anyone runs into this issue and the above answer does not apply to you, try adding a simple await page.waitForTimeout(2000). My test was completing but I was getting this error when attempting to await browser.close(); Adding the wait after searching for my final selector seems to have resolved the issue.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yaniv Efraim
Solution 2 recursivebackronym