LoginSignup
1
0

More than 1 year has passed since last update.

Chrome Extensionで選択テキストをショートカットで処理する

Last updated at Posted at 2022-05-22

動機

いちいち、複数ある拡張機能の起動をコンテキストメニューから選んで実施したくない
そもそも、Chrome-Extensionの制約として、複数のコンテキストメニューを追加すると、親メニューに包含されて、めちゃくちゃ選びづらい。
なので、選択されたテキストに対して、ショートカットキーによる操作を行えるようにする。

作成する機能

  • 選択テキストによるDeepL英日翻訳(テキスト選択後、Ctrl+Shift+Lで起動)
  • 選択テキストによる英Google検索(テキスト選択後、Ctrl+Shift+Eで起動)

全然関係無いが、Ctrl+EでChromeのアドレスバーに飛ぶので日Google検索はなし。

手順

  1. manifestにcontent_scriptsを追加する
  2. manifestにcommands(ショートカット定義)を追加する
  3. content.jsに選択テキストの変化に応じたbackground.jsへのメッセージ送信を追加する
  4. background.jsにメッセージ受信に応じた選択テキスト(グローバル変数)の更新を追加する
  5. background.jsにショートカットキーに応じた処理を追加する

manifestにcontent_scriptsを追加する

  "content_scripts": [{
    "matches": ["http://*/*","https://*/*"],
    "js": ["content-script.js"]
  }]

manifestにcommands(ショートカット定義)を追加する

  "commands": {
    "translateDeppL": {
      "suggested_key": "Ctrl+Shift+L",
      "description": "Translate Selected Text."
    },
    "searchByEnglishGoogle": {
      "suggested_key": "Ctrl+Shift+E",
      "description": "Search Text by EN Google."
    }
  }

content.jsに選択テキストの変化に応じたbackground.jsへのメッセージ送信を追加する

document.addEventListener('selectionchange', function (event) {
    let selectionText = window.getSelection().toString();
    console.log(`selection changed:${selectionText}`)

    if (selectionText.length)
        chrome.runtime.sendMessage({
            message: selectionText
        }).catch(e => console.error(e))
})

background.jsにメッセージ受信に応じた選択テキスト(グローバル変数)の更新を追加する

let selectionText
function onMessageFunc(message, sender, sendResponse) {
    chrome.tabs.query({active: true}).then(tabs => {
        const tab = tabs[0]
        console.log(`selection text[${message.message}] update by sender:${sender.tab.id}, active.tab.id:${tab.id}`)

        if (sender.tab.id === tab.id) {
            selectionText = message.message
        }
    })
    return true
}

background.jsにショートカットキーに応じた処理を追加する

chrome.commands.onCommand.addListener((command) => {
    switch (command) {
        case "translateDeppL":
            openDeepL(selectionText)
            break
        case "searchByEnglishGoogle":
            openEGoogle(selectionText)
            break
    }
    console.log(`Command "${command}" called selectionText:${selectionText}`);
});

参考にしたもの

1
0
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
1
0