Clipboard sample

This example demonstrates how to copy text to the clipboard. It is taken from the Copy / Paste data example of the Ninext sample application.
function copyToClipboard(text : text) do
#{:text navigator.clipboard.writeText(text);}#
end;
Usage Restrictions for navigator.clipboard.writeText()
The navigator.clipboard.writeText(text) API is subject to security restrictions enforced by browsers. It must be triggered directly by a user interaction (such as a button click).
If a delay or intermediate processing (such as a calculation) occurs between the user interaction and the call to writeText(), the browser no longer considers the operation to be user-initiated and blocks clipboard access to prevent abuse.
Best Practices:
- Call
navigator.clipboard.writeText(text)directly within a user event handler (e.g.,onclick). - Avoid introducing asynchronous operations or delays between the user action and the function call.
Correct Example:
document.getElementById("copyButton").addEventListener("click", () => {
navigator.clipboard.writeText("Copied text!")
.then(() => console.log("Text copied successfully!"))
.catch(err => console.error("Error copying text:", err));
});
Incorrect Example (may not work):
document.getElementById("copyButton").addEventListener("click", () => {
setTimeout(() => { // Introducing a delay may prevent copying
navigator.clipboard.writeText("Copied text!");
}, 100);
});
