Clipboard sample

image.png

This example demonstrates how to copy text to the clipboard. It is taken from the Copy / Paste data example of the Ninext sample application.

Ninox
function copyToClipboard(text : text) do
    #{ navigator.clipboard.writeText(text) }#
end;

The block carries no type annotation: it acts without returning anything. An annotation such as :text would announce a value, to be returned with return; from version 3.2.0 onwards, the Errors tab reports a typed block that returns nothing.

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:

Ninox
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):

Ninox
document.getElementById("copyButton").addEventListener("click", () => {
    setTimeout(() => { // Introducing a delay may prevent copying
        navigator.clipboard.writeText("Copied text!");
    }, 100);
});