js でテキストをコピーする clipboard を扱う

よく入力フォームのテキストをコピーするボタンがあると思うけど、
それを実装してみる。

昔は document.execCommand() を使って実装していたみたいだけど非推奨になっている。

その1 パッケージでお手軽に実装する

index.html

  • パッケージは CDN 経由で使用
  • ID で指定した入力フォームのテキストをコピーする
  • npm 経由だと navigator.clipboard ではなく clipboard でアクセスする
  • CDN 経由だと navigator.clipboard を上書きして使っている
<!doctype html>

<html>
<head>
	<meta charset="utf8">
	<title>clipboard - js html sample</title>
</head>

<body>
	<input id="InputText" type="text" name="" value="copy text">
	<button type="button" onclick="javascript:copy()">copy</button>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard-polyfill/4.0.0/es5/overwrite-globals/clipboard-polyfill.overwrite-globals.es5.js"></script>
	<script type="text/javascript">
		function copy() {
			const target = document.getElementById('InputText')
			if (!target) { return }
			navigator.clipboard.writeText(target.value).then(
				() => { console.log('success') },
				() => { console.log('failed') }
			)
		}
	</script>
</body>
</html>

その2 Vanilla JS

  • navigator.clipboard は https 化されたサイトでないと使用できないらしいので開発に不向き
  • navigator.clipboard が使えない場合は document.execCommand() を使うしかないかも

index.html

<!doctype html>

<html>
<head>
	<meta charset="utf8">
	<title>clipboard - js html sample</title>
</head>

<body>
	<input id="InputText" type="text" name="" value="copy text">
	<button type="button" onclick="javascript:copy()">copy</button>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard-polyfill/4.0.0/es5/overwrite-globals/clipboard-polyfill.overwrite-globals.es5.js"></script>
	<script type="text/javascript">
		function copy() {
			const target = document.getElementById('InputText')
			if (!target) { return }
			if (navigator.clipboard) {
				navigator.clipboard.writeText(target.value).then(
					() => { console.log('success') },
					() => { console.log('failed') }
				)
				return
			}
			target.select()
			document.execCommand('copy')
			console.log('success')
		}
	</script>
</body>
</html>
カテゴリー:js