Home > other >  A way to "cache" a value in Puppeteer's waitForFunction?
A way to "cache" a value in Puppeteer's waitForFunction?

Time:11-29

Is there a way to "cache" a value in Puppeteer's browser-based functions?

The callback passed to page.waitForFunction( .. ) is running on every DOMMutation from the puppeteer option polling: "mutation". So it could potentially run 500 times and execute const listEl = document.querySelector("#list") 500 times.

I was wondering if there is a way to cache listEl when it's found so that next time the callback is invoked querySelector("#listEl") does not have to run again and the cached value inside listEl is used.

await page.waitForFunction(
    () => {
      const listEl = document.querySelector("#list");
    },
    {
      polling: "mutation",
    }
  );
})();

The callback inside waitForFunction( ..) has no access to variables outside the function. Because the callback runs (injected) inside Browser context and the outside environment is node.js.

CodePudding user response:

You could just make it a window property:

window.listEl = window.listEl || document.querySelector("#list")

CodePudding user response:

Well you could use localStorage. As puppeteer is using chromium, localStorage is therefore supported.

await page.evaluate(() => {
  localStorage.setItem('key', 'value');
});

You could even probably pass the localStorage value through different executions on a same domain via userDataDir launch option.

const browser = await puppeteer.launch({
  userDataDir: './temp/',
  // ...
});
  • Related