剪貼簿範例

image.png

這個範例示範如何把文字複製到剪貼簿。它取自 Ninext 範例應用程式中的 Copy / Paste data 範例。

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

navigator.clipboard.writeText() 的使用限制

navigator.clipboard.writeText(text) 這個 API 受到瀏覽器的安全性限制。它必須由使用者的互動(例如點選按鈕)直接觸發。

如果在使用者互動與呼叫 writeText() 之間出現延遲或中間處理(例如某項運算),瀏覽器就不再認為這項操作是由使用者發起的,並會封鎖對剪貼簿的存取,以防濫用。

最佳做法:

  • 在使用者事件處理常式中(例如 onclick)直接呼叫 navigator.clipboard.writeText(text)
  • 避免在使用者動作與函式呼叫之間插入非同步作業或延遲。

正確範例:

document.getElementById("copyButton").addEventListener("click", () => {
    navigator.clipboard.writeText("Copied text!")
        .then(() => console.log("Text copied successfully!"))
        .catch(err => console.error("Error copying text:", err));
});

錯誤範例(可能無法運作):

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