|
| 1 | +const copyEl = document.querySelector(".copy"); |
| 2 | +const copyButton = copyEl.querySelector("button"); |
| 3 | +const copySvgArea = copyEl.querySelector(".svg-area"); |
| 4 | + |
| 5 | +const pasteEl = document.querySelector(".paste"); |
| 6 | +const pasteButton = pasteEl.querySelector("button"); |
| 7 | +const pasteSvgArea = pasteEl.querySelector(".svg-area"); |
| 8 | + |
| 9 | +const supportNotice = document.querySelector(".support-notice"); |
| 10 | + |
| 11 | +// Start by loading the edge.svg image and displaying it in the copy area. |
| 12 | +fetch("edge.svg") |
| 13 | + .then((response) => response.text()) |
| 14 | + .then((text) => (copySvgArea.innerHTML = text)); |
| 15 | + |
| 16 | +// Update the support notice based on the browser's capabilities. |
| 17 | +const supportsSVG = ("supports" in window.ClipboardItem) && window.ClipboardItem.supports("image/svg+xml"); |
| 18 | +if (!supportsSVG) { |
| 19 | + supportNotice.classList.add("no-support"); |
| 20 | + supportNotice.textContent = "Your browser does not support reading or writing SVG to the clipboard."; |
| 21 | +} |
| 22 | + |
| 23 | +copyButton.addEventListener("click", async () => { |
| 24 | + if (!supportsSVG) { |
| 25 | + return; |
| 26 | + } |
| 27 | + |
| 28 | + // Get the SVG image as a Blob. |
| 29 | + const response = await fetch("edge.svg"); |
| 30 | + const blob = await response.blob(); |
| 31 | + |
| 32 | + // Store the SVG content in the clipboard. |
| 33 | + await navigator.clipboard.write([ |
| 34 | + new window.ClipboardItem({ |
| 35 | + [blob.type]: blob |
| 36 | + }), |
| 37 | + ]); |
| 38 | +}); |
| 39 | + |
| 40 | +pasteButton.addEventListener("click", async () => { |
| 41 | + if (!supportsSVG) { |
| 42 | + return; |
| 43 | + } |
| 44 | + |
| 45 | + // On paste, read the system clipboard. |
| 46 | + const [clipboardItem] = await navigator.clipboard.read(); |
| 47 | + const svgBlob = await clipboardItem.getType("image/svg+xml"); |
| 48 | + if (!svgBlob) { |
| 49 | + alert("No SVG in the clipboard."); |
| 50 | + return; |
| 51 | + } |
| 52 | + |
| 53 | + // Getting the source code here, since :hover effects don't |
| 54 | + // work when the SVG is referenced as `<img src>`. |
| 55 | + const svgCode = await svgBlob.text(); |
| 56 | + pasteSvgArea.innerHTML = svgCode; |
| 57 | +}); |
0 commit comments