欣迪

最近因工作關係,要使用遊戲引擎開發。

碰到一個超怪的問題,我在 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 那些都不行…

訂閱 IT-Monk

訂閱最新文章的發布消息! 😚😚😚
Loading

作者介紹 - 欣迪

欣迪

從設計到寫程式,發現自己有追求前端技巧的自虐傾向。不斷的踩坑,再從坑裡爬出來,慢慢對攀岩有點心得。 目前在多間公司擔任網站設計顧問。 同時也是網站架設公司負責人。