コンテンツにスキップ

DOMContentLoaded を使う

run_atdocument_startを設定する。拡張機能ではこれを設定しておかないとイベントが発火しない。

manifest.json
1
2
3
4
5
6
7
8
9
{
  "content_scripts": [
    {
      "matches": ["file://*/*"],
      "js": ["content.js"],
      "run_at": "document_start"
    }
  ]
}
content.js
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
console.log("Chrome Extension Test");

function appendElement(innerText) {
  const div = document.createElement("div");
  div.innerText = innerText;
  console.log(document.body.innerHTML);
  document.body.prepend(div);
}

window.addEventListener("DOMContentLoaded", () => {
  console.log("Chrome Extension Test: DOMContentLoaded");
  appendElement("Chrome Extension Test: DOMContentLoaded");
});

以下の順番で実行されるようだ。

  1. 拡張機能のDOMContentLoaded
  2. ページのDOMContentLoaded
  3. 拡張機能のload
  4. ページのload