How to evaluate the results out of script with type module when using addScriptTag

Viewed 344

I am trying to use addScriptTag to use some modules on a page.

(async () => {
  const browser = await launch();
  const page = await browser.newPage();
  page.on("console", (c) => console.log(c.text()));
  page.on("error", (c) => console.error(c.message));
  await page.goto("https://example.com");
  await page.addScriptTag({
    path: resolve(__dirname, "verbs.js"),
    type: "module"
  });
  await browser.close(); // <==== Closes before "verbs.js" finishes doing it thing
})();

verbs.js:

import nlp from "https://unpkg.com/compromise@13.3.1/builds/compromise.mjs";

const selectors = "p, h1, h2, h3, h4, h5, h6";
const links = [...document.querySelectorAll(selectors)];
const pageText = links.map((node) => node.textContent).join("");

const doc = nlp(pageText);

const res = doc
  .verbs()
  .json()
  .map((noun) => noun.text);

export default res; // I need a way of accessing res from node context

Also how can I evaluate the result out of a module?

I guess what I am looking for is a way to get some sort of exported results from the module. like to read it default export.

1 Answers

Maybe you could use page.exposeFunction()?

At the end of the main script:

(async () => {
  // ...
  await page.exposeFunction('useRes', (res) => {
    // use res
    await browser.close();
  });
  await page.addScriptTag(/* ... */);
})();

At the end of verbs.js:

// ...
window.useRes(res);
Related