Chrome 拡張を使って今開いているタブの DOM を操作する


Content Scripts を使う。

ボタン押下とかショートカットキーとかそういうイベントで操作したいなら、
Background から content script のイベントハンドラを呼ぶことになる。

以下、 選択したテキストを<samp>要素でラップする例。

content.js
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    if (request.text == "code-block") {
        const selection = window.getSelection().toString().replace(/\n/g, "<br/>");
        const insertContent = `<samp>${selection}</samp>`;
        document.execCommand("insertHTML", false, insertContent);
        sendResponse({ "text": insertContent });
    }
});
background.js
chrome.commands.onCommand.addListener(function (command) {
    if (command === 'code-block') {
        chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
            chrome.tabs.sendMessage(tabs[0].id, { text: "code-block" }, function (response) {
                console.log(response);
            });
        });
    }
});
manifest.json
{
  "name": "Encode",
  "version": "0.0.2",
  "description": "Make a string to a code block.",
  "manifest_version": 2,
  "permissions": [
    "activeTab"
  ],
  "background": {
    "scripts": [
      "background.js"
    ],
    "persistent": false
  },
  "content_scripts": [
    {
      "matches": [
        "http://*/*",
        "https://*/*"
      ],
      "js": [
        "content.js"
      ]
    }
  ],
  "commands": {
    "code-block": {
      "suggested_key": {
        "default": "Ctrl+Shift+Y",
        "mac": "Command+Shift+Y"
      },
      "description": "Make selected text to a code block."
    }
  }
}

関連記事