2

Is there a shorter method to wait for complicated selector?

await page.evaluate(() => {
  return new Promise(resolve => {
     var aid = setInterval(function(){
        let block = $('div[class="asset"]:contains("Assets Folder")');

        if(block.length){
           clearInterval(aid);
           block.click();
           resolve();
        }

     }, 100);
  })
});

page.waitFor() throws an error:

Error: Evaluation failed: DOMException: Failed to execute 'querySelector' on 'Document': 'div[class="asset"]:contains("Assets Folder")' is not a valid selector.

Grant Miller
  • 24,187
  • 16
  • 134
  • 150
John Lenson
  • 157
  • 2
  • 8
  • If i remember correctly, the `:contains()` selector only works with jQuery. See [this question](https://stackoverflow.com/questions/1520429/is-there-a-css-selector-for-elements-containing-certain-text) – Martijn Vissers Oct 30 '18 at 12:01
  • Ok, so maybe there is shorter workaround, without `evaluate + promise + setinterval` chain? – John Lenson Oct 30 '18 at 13:28

1 Answers1

7

page.waitForFunction()

You can use page.waitForFunction() to wait for a given function to return a truthy value.

Keep in mind that the :contains() selector is part of the jQuery API and not a standard CSS selector.

Therefore, instead, you can wait until some element (at least one) in an array of nodes matching the selector has textContent which includes the specified text and is present in the DOM:

await page.waitForFunction(() =>
  [...document.querySelectorAll('div[class="asset"]')].some(e => e.textContent.includes('Assets Folder'))
);

page.waitForXPath()

Alternatively, XPath includes a contains() function, so you can use page.waitForXPath() with a corresponding XPath expression to wait for your element to be added to the DOM:

await page.waitForXPath('//*[contains(text(), "Assets Folder")]/ancestor-or-self::div[@class="asset"]');
Grant Miller
  • 24,187
  • 16
  • 134
  • 150