LoginSignup
2
6

More than 1 year has passed since last update.

【JavaScript】クリップボードコピー(navigator.clipboard.writeText)が使えないときの対応方法

Last updated at Posted at 2022-05-16

端末&ブラウザによって、クリップボードコピー(navigator.clipboard.writeText)が使えなかったので、
使えないときの対応を行いました。そのメモを残しておきます。誰かの助けになれば幸いです。

対応方針① window.clipboardData.setData

以下の記事を読むと

navigator.clipboardが使えないときは、window.clipboardData.setData('Text', ~~) で代替できると書いてありました。

しかし、window.clipboardDataのclipboardDataが色々とやってみても使えなかったため、断念しました。
(※ 何かwindowオブジェクトの設定がミスってるのかも)

var clipboardText = "clipboard";
if(navigator.clipboard == undefined) {
  window.clipboardData.setData('Text', clipboardText);
} else {
  navigator.clipboard.writeText(clipboardText);
}

対応方針② document.execCommand

以下の記事を読んで

document.execCommandを使ったところうまくいきました。

ただ、「document.execCommand」は非推奨なので、あまり使いたくなかったですが、今後、navigator.clipboardがすべてのブラウザ&端末で使えるようになると思うので(たぶん)、一旦のように書けます

export const copyTextToClipboard = (text: string): void => {
  if (navigator.clipboard) return  navigator.clipboard.writeText(text);

  const isIos = navigator.userAgent.match(/ipad|iphone/i);
  const textarea = document.createElement('textarea');
  textarea.value = text;
  document.body.appendChild(textarea);
  if (isIos) {
    const range = document.createRange();
    range.selectNodeContents(textarea);
    const selection = window.getSelection();
    selection?.removeAllRanges();
    selection?.addRange(range);
    textarea.setSelectionRange(0, 999999);
  } else {
    textarea.select();
  }
  const result = document.execCommand('copy');
  document.body.removeChild(textarea);
};

「navigator.clipboard」が使えるときは使って、使えないときは、「document.execCommand」を使うようにしました。

最後に一言

何か間違っている点があれば、教えて頂けたら幸いです。
よろしくお願い致します。
また「いいね!」してもらえるとすごい嬉しいです!!

2
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
6