Skip to content
Snippets Groups Projects
common.ts 1.51 KiB
// this is a Node module. require is a must to work across different envs
const URL = require("url-parse");

const DUMMY_QR_CODE_ID = "dummyQrCode";

export const ELEMENT_TYPES_TO_REMOVE = {
  br: true,
  hr: true,
  use: true,
  svg: true,
};

export const ATTRIBUTES_TO_KEEP = {
  alt: true,
  src: true,
  cite: true,
  data: true,
  datetime: true,
  href: true,
  value: true,
};

export const amendNodes = (document: HTMLDocument): void => {
  /**
   * Unwind Outlook safelink wrappers
   */
  const anchors = document.getElementsByTagName("a");
  for (const anchor of anchors) {
    const url = new URL(anchor.getAttribute("href"), true);

    if (url.host.includes("safelinks.protection.outlook.com")) {
      anchor.setAttribute("href", url.query["url"]);
    }
  }
};

/**
 * Removes dummy QR code from HTML
 * @param element
 */
const isDummyQrCode = (element: HTMLElement): boolean => {
  if (element.id === DUMMY_QR_CODE_ID) {
    return true;
  }
};

/**
 * Decides whether node should be removed
 * @param element
 */
export const pruneElement = (element: HTMLElement): boolean => {
  if (isDummyQrCode(element)) {
    return true;
  }

  return !!ELEMENT_TYPES_TO_REMOVE[element.nodeName.toLowerCase()];
};

export const cloneAnchorFromPane = (
  a: HTMLAnchorElement,
  pane: HTMLElement
): void => {
  try {
    const url = new URL(a.getAttribute("href"));
    // If this is external url
    if (url.host && url.protocol) {
      pane.parentNode.insertBefore(a.cloneNode(false), pane);
    }
  } catch (e) {
    return e;
  }
};