const ALLOWED_PROTOCOLS = new Set(["http:", "https:", "mailto:", "tel:"]);

/** Main-page side of the reader's links — see `sendNavigateMessage` (lisio-broadcast-channel-controller.ts). */
async function lisioNavigateChannelHandler(
  this: unknown,
  datas: string,
) {
  const { href, blank } = JSON.parse(datas) as { href: string; blank: boolean };
  let url: URL;
  try {
    url = new URL(href, window.location.href);
  } catch {
    return;
  }
  // Never let the channel run a javascript:/data: URL in the main page.
  if (!ALLOWED_PROTOCOLS.has(url.protocol)) {
    return;
  }
  if (blank) {
    window.open(url.href, "_blank");
  } else {
    window.location.href = url.href;
  }
}

export default lisioNavigateChannelHandler;
