showcase
- v0.2.4
- 37 commits
- 1 branch
- 6 tags
- updated
- CI 2/2
copy.js
1.4 KB · 30 lines
1// Copy buttons, as progressive enhancement: without JS the buttons stay2// hidden and the text can still be copied by hand. data-copy names a3// read-only field, whose value is copied, or a link to a raw file, which is4// fetched and copied as it is (the CSP allows fetches to this origin only).5// Nothing inline: the CSP forbids it.6function copyFile(url) {7 const file = fetch(url).then((r) => (r.ok ? r.blob() : Promise.reject(new Error(r.statusText))));8 // Safari only allows clipboard writes during the click, so the9 // download goes in as a promise; elsewhere writeText after it is fine.10 if (window.ClipboardItem) {11 const blob = file.then((b) => new Blob([b], { type: "text/plain" }));12 return navigator.clipboard.write([new ClipboardItem({ "text/plain": blob })]);13 }14 return file.then((b) => b.text()).then((t) => navigator.clipboard.writeText(t));15}1617for (const button of document.querySelectorAll("button[data-copy]")) {18 const field = document.getElementById(button.dataset.copy);19 if (!field || !navigator.clipboard) continue;20 button.hidden = false;21 button.addEventListener("click", async () => {22 try {23 await (field.href ? copyFile(field.href) : navigator.clipboard.writeText(field.value));24 button.classList.add("copied");25 setTimeout(() => button.classList.remove("copied"), 1500);26 } catch {27 field.select?.();28 }29 });30}