最近因工作關係,要使用遊戲引擎開發。
碰到一個超怪的問題,我在 canvas 上設置了按鈕,並使用 touchstart 去觸發。除了 iphone 以外,全部的裝置都可以正常使用。複製的 function 如下:
export function copyToClipboard(text: string): Promise<void> {
return new Promise((resolve, reject) => {
const el = document.createElement("textarea");
el.value = text;
el.setAttribute("readonly", "");
el.style.contain = "strict";
el.style.position = "absolute";
el.style.left = "-9999px";
el.style.fontSize = "12pt";
document.body.appendChild(el);
const copyText = el;
// Select the text field
copyText.select();
copyText.setSelectionRange(0, 99999); // For mobile devices
navigator.clipboard
.writeText(copyText.value)
.then(() => {
resolve();
})
.catch((e) => {
reject(e);
});
});
}
用 iPhone 打開出現了 Permission 相關的 issue。
這問題大概困擾了我兩天。使用了遊戲引擎內建的按鈕綁定 copy function,卻可以成功。
最後爬到這篇文章: Copy to clipboard using Javascript in iOS – Stack Overflow
好樣的 iPhone 只能經由 “click” 來觸發複製文字的程式碼。也就是說,類似的 touchstart, touchend 那些都不行…
