21
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2018-10-27

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."
    }
  }
}

関連記事

21
14
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
21
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?