LoginSignup
1
0

More than 3 years have passed since last update.

短期的なイベントハンドラー(短命なイベントハンドラー)は5秒未満

Posted at

原文で言うa short-lived event handlerの定義が不明だった。

JavaScriptによるクリップボード操作にはユーザーの許可を得ずに実行できるパターンがある。
それがユーザー生成の短期的なイベントハンドラー内での実行であるが、
ユーザー生成の短期的なイベントハンドラーでないときにパーミッションを取らずに実行するとFirefoxの場合下記の警告が出力される。(コピーは失敗する)
document.execCommand(‘cut’/‘copy’) はユーザー生成の短期的なイベントハンドラーの内部からの呼び出しでないため拒否されました。

今回は一般的に短期的なイベントハンドラーとして紹介されるclickイベント内で警告が出た。

今までの実績ある実装との違いは、

  • async functionである
  • awaitを使っている
  • fetchを使っている
  • (fech処理の関係上)クリックからexecCommand実行まで時間が空く

であった。
順番にテストした結果、およそ5秒を過ぎるとclickイベント内でも短命とみなされず失敗するという結果が得られた。

察するに、

ユーザー操作に対する短命なイベントハンドラー(例えば click ハンドラー)

の「例えば click ハンドラー」は「ユーザー操作に対する(イベントハンドラー)」にかかっており、「短命」かどうかはユーザー操作関係なく、コード量にも関係なく、字面どおりに「短時間」であることが必要かと思われる。

私は「ユーザー操作に対するイベントハンドラー」≒clickイベント自体が「短命なイベントハンドラー」だと解釈していた。

コード

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<button id="test">copy</button>
</body>
<script type="text/javascript">

function sleep (ms) {
    return new Promise((res) => { setTimeout(res, ms)})
}

document.querySelector('#test').addEventListener('click',async () => {
    await sleep(5 * 1000)
    document.execCommand('copy')
    console.log('copy')
})
</script>
</html>

await sleep(5 * 1000)では失敗
await sleep(4 * 1000)では成功
await sleep(4800)あたりから成功

参考

document.execCommand をユーザー操作に対する短命なイベントハンドラー(例えば click ハンドラー)のなかで実行することで、特別な許可なしに"切り取り"や"コピー"などのクリップボード操作が可能になります。

The document.execCommand() method's "cut" and "copy" commands can be used to replace the clipboard's current contents with the selected material. These commands can be used without any special permission if you are using them in a short-lived event handler for a user action (for example, a click handler).

In my browser the countdown stops after around 5 seconds. If I press Ctrl+C after the chain of copy handlers was broken, the copy handler is invoked again by a user generated event then it goes for 5 seconds again.

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