Skip to content

Instantly share code, notes, and snippets.

@Kilian
Created April 17, 2020 14:47
Show Gist options
  • Save Kilian/d3f86eb2910cadb839cc5387bcbfbd23 to your computer and use it in GitHub Desktop.
Save Kilian/d3f86eb2910cadb839cc5387bcbfbd23 to your computer and use it in GitHub Desktop.

Revisions

  1. Kilian created this gist Apr 17, 2020.
    43 changes: 43 additions & 0 deletions convertMailto.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@
    const convertMailto = () => {
    const copyToClipboard = str => {
    const el = document.createElement("textarea");
    el.value = str;
    el.setAttribute("readonly", "");
    el.style.position = "absolute";
    el.style.opacity = "0";
    el.style.pointerEvents = 'none';
    document.body.appendChild(el);

    const selected =
    document.getSelection().rangeCount > 0
    ? document.getSelection().getRangeAt(0)
    : false;

    el.select();
    document.execCommand("copy");
    document.body.removeChild(el);

    if (selected) {
    document.getSelection().removeAllRanges();
    document.getSelection().addRange(selected);
    }
    };

    const emails = Array.from(
    document.querySelectorAll(`a[href^="mailto:"]`)
    );
    emails.forEach(email => {
    email.addEventListener("click", e => {
    e.preventDefault();

    const email = e.target
    .getAttribute("href")
    .split("mailto:")[1]
    .split("?")[0];

    copyToClipboard(email);
    });
    });
    };

    convertMailto();