node-html-to-image icon indicating copy to clipboard operation
node-html-to-image copied to clipboard

Unable to use beforeScreenshot parameter for intercepting XHR

Open justinherter opened this issue 2 years ago • 1 comments
trafficstars

It seems that beforeScreenshot (when provided) is called after rendering the provided html, and just before the screenshot as seen below. However we have limited control of the Page prior to rendering. If I move the beforeScreenshot call prior to the setContent, this enables us to do things like intercept HTTP/XHR requests.

  await page.setContent(screenshot.html, { waitUntil });
  const element = await page.$(screenshot.selector);
  if (!element) {
    throw Error("No element matches selector: " + screenshot.selector);
  }

  if (isFunction(beforeScreenshot)) {
    await beforeScreenshot(page);
  }

  const buffer = await element.screenshot({
    path: screenshot.output,
    type: screenshot.type,
    omitBackground: screenshot.transparent,
    encoding: screenshot.encoding,
    quality: screenshot.quality,
  });

I would like to propose the addition of a beforeRendering parameter that allows for more control of the page prior to rendering. This example intercepts XHR requests.

beforeRendering: (page: Page): void => {
  page.on('request', (interceptedRequest) => {
    if (interceptedRequest.url().endsWith('.jpg')) {
      interceptedRequest.respond({
        status: 200,
        contentType: 'image/jpeg',
        body: Buffer.from(localResource.content, 'base64'),
      });
    } 
    else { interceptedRequest.continue(); }
  });
};

If you are open to it i can submit a PR, as I would rather use this lib as built rather than forking it. Alternatively we could execute the beforeScreenshot prior to setting the content. Im not sure of the implications in doing so but it has proven the concept. Thanks!

justinherter avatar Aug 11 '23 18:08 justinherter

Hi @justinherter 👋 Thank you for opening this issue. I like the idea of a beforeRendering function 👍 Feel free to open a pull request 😄

frinyvonnick avatar Aug 13 '23 08:08 frinyvonnick