LoginSignup
0
0

More than 3 years have passed since last update.

クリックイベントを createEvent で発火させると getSelection は取れない

Posted at

ドキュメントで確認が取れたわけではないけれど、動作確認をするとそのように感じるのでメモ。

例えば以下のように createEvent で任意の座標をクリックさせるイベントを発火させる。そしてクリックした位置にあるテキストの Range オブジェクトを取得するために window.getSelection() を使う。が、これだと Range オブジェクトは取得できない。

const elm = document.getElementById('hoge')

elm.addEventListener('click', () => {
  const sel = window.getSelection()
  sel.getRangeAt(0) // error
})

const evt = document.createEvent('MouseEvents')
evt.initMouseEvent('click', true, true, window, 0, 0, 0, 100, 200, false, false, false, false, 0, null)
elm.dispatchEvent(evt)

createEvent で発火されたイベントの isTrustedfalse になっている。つまりユーザ自身が能動的に起こしたイベントではない。推測だがセキュリティ的な問題で Range オブジェクトが取得できないのかもしれない。

回避策というか普通はこちら

わざわざ window.getSelection() を使わなくても caretPositionFromPoint / caretRangeFromPoint を使えば指定座標の Range オブジェクトが取得できる。

if (document.caretRangeFromPoint) {
  const range = document.caretRangeFromPoint(x, y)
  const elm = document.elementFromPoint(x, y)
} else {
  // Firefox は caretRangeFromPoint がないのでこちら
  const pos = document.caretPositionFromPoint(x, y)
  const elm = document.elementFromPoint(x, y)
  const range = document.createRange()
  range.setStart(pos.offsetNode, pos.offset)
}
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