0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ブックマークレットでテキストの貼り付けを行う方法

Posted at

TL; DR

  • prompt() を使う

背景

自動化のためブックマークレットでクリップボードからDOMの特定要素へ貼り付けを行うツールを作成していましたが、navigator.clipboard.readText() が想定通りに動作しませんでした。

clipboard APIは document にフォーカスが当たっているときにしか実行されません。そのため、ブックマークレットをクリックした瞬間にはフォーカスが当たっておらずエラーが発生してしまいます。

以下の記事で詳しく解説されています。

コピー (navigator.clipboard.writeText()) の場合上記記事のように setTimeout() で非同期実行することでエラーを回避できますが、 readText() の場合はこちらも動作しませんでした。

解決方法

やりたいこと的にclipboard APIにこだわる必要はなかったので、原始的ですが prompt() で入力画面を表示、そこにユーザー入力を入れてもらうことで対処しました。

入力をconsole.logへ表示
javascript:console.log(prompt("user input: "))

prompt.png

output.png

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?