使用 js 複製貼上剪貼簿發生 Uncaught (in promise) DOMException: Document is not focused.

我一開始照上面的範例做,想要用 JavaScript 來複製文字,但發現怎麼樣都複製失敗。後來發現就連他給的第一個範例點進去也不能複製。

現在發現可能是最後複製完後馬上 alert ,造成實際複製時,不是 focus 在目標頁面上造成的。在複製的過程中會檢查目前游標或是關注區 (focus) 是否在同個 document 頁面中。由於複製過程是 asynchrounously ,如果沒有用 async/await 或是其他非同步的技巧控制,會很快地執行到 alert 這行,跳出警告視窗。雖然看似複製完成,但其實複製仍在背景執行中,尚未完成。當跳出警告視窗時,就沒有 focus 在原本的頁面中了。如果這時複製仍然正在進行,就會失敗。

解法

可選擇以下任一。

  • 移除 alert 那行
  • 使用 async/await (見下列範例)
async function myFunction() {
/* Get the text field */
var copyText = document.getElementById("myInput");
/* Select the text field */
copyText.select();
copyText.setSelectionRange(0, 99999); /* For mobile devices */
/* Copy the text inside the text field */
await navigator.clipboard.writeText(copyText.value);

/* Alert the copied text */

}

正確的複製姿勢

如果你在找範例程式碼,建議參考以下這篇。我覺得寫的比較好,且觀念完整。

--

--