How-to
Website
Web app
Copy to the clipboard
A Copy button saves the reader selecting a link by hand. To copy text, call the browser's clipboard from an action and say when it worked:
page Share(path: "/share", title: "Share", description: "Copy the link.") {
state copied = false
state failed = false
action copy(text: String) {
copied = false
failed = false
try {
await navigator.clipboard.writeText(text)
copied = true
} catch e {
failed = true
}
}
Heading("Share").h1
Button("Copy the link") { on click { copy(location.href) } }
if copied { Toast("Copied").success }
if failed { Toast("Could not copy. Select the address and copy it by hand.").danger }
}
How it works
navigator.clipboardandlocationare browser globals, used as written with no prefix.writeTextreturns a promise, so the action awaits it.awaitmakes the action async, andcopiedis set only once the text is on the clipboard.- The browser may refuse: the page is not focused, it is not served over HTTPS, or the reader denied the permission. The promise then rejects, the
catchsetsfailed, and the reader is told to copy by hand instead of seeing nothing. - The button's click handler calls
copywith the page's own address. - A
Toastshows once, when its branch is drawn. The action setscopiedandfailedback tofalsebefore it starts, so the branch is drawn again on every click and a second copy shows a second toast. Without that,copiedwould staytrueand the second click would show nothing.