Featured image of post How to get a hyperlink from the clipboard

How to get a hyperlink from the clipboard

The following function can get a hyperlink from the clipboard.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
export async function getLinkFromClipboard(e: ClipboardEvent) {
  if (!e.clipboardData) return;

  const htmlText = e.clipboardData.getData("text/html");
  if (!htmlText) {
    return;
  }

  const parser = new DOMParser();
  const doc = parser.parseFromString(htmlText, "text/html");
  const anchor = doc.querySelector("a");
  if (!anchor) {
    return;
  }

  return anchor.href;
}

To use this function in Svelte, you can do something like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<script>
  // ...

  let linkInput: HTMLInputElement;
  async function handlePaste(e: ClipboardEvent) {
    const url = await getLinkFromClipboard(e);
    if (url) linkInput.value = url;
    setToastState({ type: "success", message: "Updated link" });
  }
</script>

<input type="text" bind:this={linkInput} on:paste={handlePaste} />
Built with Hugo
Theme Stack designed by Jimmy