diff --git a/core/scope.js b/core/scope.js index 74e84161..f146c776 100644 --- a/core/scope.js +++ b/core/scope.js @@ -1,7 +1,7 @@ /** * phantomas browser "scope" with helper code * - * Code below is executed in page's "scope" (injected by lib/browser.js) + * Code below is executed in page's "scope" (injected by the scope.injectJs() helper) */ /* istanbul ignore next */ (function coreScope(scope) { diff --git a/lib/browser.js b/lib/browser.js index 313b88aa..9a11fff5 100644 --- a/lib/browser.js +++ b/lib/browser.js @@ -179,7 +179,7 @@ Browser.prototype.init = async (phantomasOptions) => { var meta = responses[data.requestId]; /* istanbul ignore if */ - if (typeof meta === "undefined") { + if (typeof meta?.response === "undefined") { // the browser sometimes looses trace of a request, let's ignore. networkDebug( "Can't find request id %d in previous requests", diff --git a/lib/index.js b/lib/index.js index 11af35cf..de3dc855 100644 --- a/lib/index.js +++ b/lib/index.js @@ -89,7 +89,10 @@ function phantomas(url, opts) { return page.$$(selector); }, - // @see https://github.com/GoogleChrome/puppeteer/blob/v1.11.0/docs/api.md#pageevaluateonnewdocumentpagefunction-args + // @see https://pptr.dev/api/puppeteer.page.evaluateonnewdocument + // Adds a function which would be invoked in when: + // - the child frame is attached or navigated + // - the page is navigated injectJs: async (script) => { const debug = require("debug")("phantomas:injectJs"); @@ -98,7 +101,9 @@ function phantomas(url, opts) { suffix = "}"; const preloadFile = - prefix + require("fs").readFileSync(script, "utf8") + suffix; + prefix + + (await require("fs/promises").readFile(script, "utf8")) + + suffix; await page.evaluateOnNewDocument(preloadFile); @@ -117,8 +122,9 @@ function phantomas(url, opts) { // @see https://github.com/GoogleChrome/puppeteer/blob/v1.11.0/docs/api.md#pageexposefunctionname-puppeteerfunction await page.exposeFunction("__phantomas_emit", scope.emit); - // Inject helper code into the browser's scope - events.on("init", () => { + // Inject helper code into the browser's scope (but only once!) + events.once("init", () => { + debug("onInit: injecting the core/scope.js ..."); scope.injectJs(__dirname + "/../core/scope.js"); }); diff --git a/modules/domComplexity/scope.js b/modules/domComplexity/scope.js index 8eba9e9a..ace830b2 100644 --- a/modules/domComplexity/scope.js +++ b/modules/domComplexity/scope.js @@ -92,13 +92,17 @@ })(); // count