16

How can I wait until an element has a certain value?

For example, some button on a page changes the value of an input field from "No Value" to "Value X". The problem is, I don't know how much time will it take so page.waitFor() is not an option.

I thought I could use page.waitForSelector(input:contains('No Value')); but that does not work as far as I understand.

Possibly page.waitForFunction() should work, but I am not sure what function to write there. Would I use a page.evaluate that returns the value of the input maybe?

ggorlen
  • 44,755
  • 7
  • 76
  • 106
kmeshavkin
  • 325
  • 1
  • 2
  • 12

1 Answers1

30

According to docs page.waitForFunction will wait until the function passed to it (as a closure or a string) returns a truthy value.

const puppeteer = require('puppeteer');

puppeteer.launch({headless : false}).then(async browser => {
  const page = await browser.newPage();
  await page.goto(url);
  await page.waitForFunction('document.getElementById("wait").value != "No Value"');
  console.log('Value changed!');
  await browser.close();
});
Bruno Degomme
  • 883
  • 10
  • 11
Vaviloff
  • 16,282
  • 6
  • 48
  • 56
  • How would this `waitForFunction` function call look like when using ElementHandles? – Ini Mar 10 '21 at 21:47
  • @Ini Sorry can't advise on that, honestly I always prefer the explicit nature of `page.evaluate` and never ever even touch handles. – Vaviloff Mar 11 '21 at 02:50
  • No problem. I just think that using a string for code looks IMO pretty horrible (`'document.getElementById("wait").value != "No Value"'`) – Ini Mar 12 '21 at 00:06
  • 1
    I feel quite the opposite way :) to me it feels short and simple enough. – Vaviloff Mar 12 '21 at 07:41
  • @Ini try this: `await page.waitForFunction(\`document.getElementById("wait").value != "No Value"\`);` – Baris Senyerli Aug 31 '22 at 14:26