How to use DOMPurify hooks with async/await functions

462 Views Asked by At

In a nodejs server, using DOMPurify+JSDOM, I need to download an image inside the Hook afterSanitizeElements.

For example, using the code below, I manage to get the image, but too late, and the image cannot be leveraged to be used in the code that calls purify.sanitize.

I need the code to run in sequence in time, for console.log(clean) to show, for example, the base64 string and not the 'src' like a url.


purify.addHook('afterSanitizeElements', async (node) => {
  // Do something with the current node and return it
  // You can also mutate hookEvent (i.e. set hookEvent.forceKeepAttr = true)
  if (node.tagName) {
    if (node.tagName.toLowerCase() == 'img') {
      if (node.hasAttribute('src')) {
        if (regUrlWeb.test(node.src)) {
          const base64 = await getImageBase64(node.src);
          node.setAttribute('src', base64);
        }
      }
    }
  }
  return node;
});

const getImageBase64 = async (url: string) => {
  const image = await axios.get(url, { responseType: 'arraybuffer' });
  return Buffer.from(image.data).toString('base64');;
};

const clean = await purify.sanitize(dirty);

console.log(clean);
0

There are 0 best solutions below