2
2

More than 1 year has passed since last update.

[javascript] isTrusted=trueな疑似クリックを作る

Last updated at Posted at 2022-02-15

isTrusted

ブラウザ上で発生するEvent(clickとか)にはisTrustedというプロパティがついている。
https://developer.mozilla.org/en-US/docs/Web/API/Event/isTrusted
ユーザーが実際にElementをクリックした時はisTrusted=trueだが、例えば:

const button = getElementById("button");
button.click();

などによるjavascriptで生成された疑似クリックではisTrusted=falseとなる。

isTrusted=trueのイベントを作りたい

isTrustedはRead-onlyプロパティなので外部から変更することはできないし、そもそも疑似クリックはTrustされるべきではない(そらそう)。しかしどうしてもisTrusted=trueなクリックを作りたい時はある(ブラウザ拡張作りたい時とか)ので調べてみた。セキュリティに関しては自己責任でお願いします

コード

Element.prototype._addEventListener = Element.prototype.addEventListener;
Element.prototype.addEventListener = function () {
  let args = [...arguments];
  let temp = args[1];
    args[1] = function () {
    let args2 = [...arguments];
      args2[0] = Object.assign({}, args2[0]);
      args2[0].isTrusted = true;
      return temp(...args2);
    };
  return this._addEventListener(...args);
};

Element.protype.addEventListenerの第二引数を書き換える方法。

const button = document.getElementById("button");
button.addEventListener("click", (e) => {
  console.log(e.isTrusted);
});
button.click();
// "true"を出力

書き換えた後のaddEventListenerは全てisTrusted=trueになっている!

参考

このスレ より抜粋。他にもpuppeteerを使う方法とか別言語のスクリプトでイベント生成させる方法とかあったけど、↑が一番楽と思う。ご高覧いただきありがとうございました。

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