【Chrome拡張機能】タブを開いた後のブラウザのDom取得

【Chrome拡張機能】タブを開いた後のブラウザのDom取得

Chrome拡張機能のbackground.jsで新規tabを開いた後、開いたタブのDom操作をするのに苦戦したため、メモに残しておきます。

popup.js → background.js → contents.jsの流れで実行していくことで実現できました。

Popup.js

popup.jsにbackground.jsに情報連携するコードを記載します。例えば、コードになります。popup.htmlのIDがbtnのbuttonをクリックした際に実行されることを想定しています。

function getInfo() {

  /*  この部分で現在のdomから情報を取得したりする */

  chrome.storage.local.set({ key: コンテンツスクリプトに連携するデータ})
    .then(() => {
        console.log("データを設定");
    });

  let data = {
    url: "新規で開くタブのURL",
  };

  //background.jsを呼び出すコード
  chrome.runtime.sendMessage(data, (receive) => {
    console.log(receive);
  });

document.getElementById("btn").addEventListener("click",  () => {
  let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  chrome.scripting
    .executeScript({
      target: { tabId: tab.id },
      func: getInfo,
    })
    .then(function (r) {});
});

background.js

次にpopup.jsから送られてきたデータを取得し、新規タブを開く。

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  //新規タブを開く、requestには、popup.jsのdataに指定したデータが入ってくる
  chrome.tabs.create(
    {
      url: request.url,
    },(tab) => {
      //コンテンツスクリプトを指定して実行させる
      chrome.scripting.executeScript({
        target: { tabId: tab.id },
        files: ['./コンテンツスクリプト.js'],
      });
      sendResponse({ request });
    }
  );
});

Contents.js

background.jsのchrome.scripting.executeScriptによって呼び出されたコンテンツスクリプトを実行する。例えば以下のような感じです。

//popup.jsで格納したデータを取得して、それを使って処理する
chrome.storage.local.get(["key"]).then((result) => {
  //以下のようにjavascriptでdomを取得すると開いたタブのdomが取得できます。
  //result.keyにはpopup.jsで格納した情報が使えるのでresult.keyなどで取得できます。
  console.log(result.key);
  document.getElementById("DomのID").value = result.key;
   
});

manifest.json

最後にpopup.jsでstorageを格納するときに必要な設定は、コンテンツスクリプトを指定するための設定などをmanifest.jsonに指定します。

{
  "name": "拡張機能名",
  "description": "拡張機能の説明",
  "version": "1.0",
  "manifest_version": 3,
  "action": {
    "default_popup": "popup.html"
  },
  "background": {
    "service_worker": "background.js"
  },
  //storageなどをしようするための権限設定
  "permissions": ["activeTab", "scripting", "storage"],
  "host_permissions": ["https://*/*", "http://*/*"],
  //コンテンツスクリプトの指定
  "content_scripts": [
    {
      "matches": [
        "http://*/*",
        "https://*/*"
      ],
      "js": [
        "content.js"
      ]
    }
  ]
}

以上です。

Chrome拡張機能カテゴリの最新記事