動機
いちいち、複数ある拡張機能の起動をコンテキストメニューから選んで実施したくない
そもそも、Chrome-Extensionの制約として、複数のコンテキストメニューを追加すると、親メニューに包含されて、めちゃくちゃ選びづらい。
なので、選択されたテキストに対して、ショートカットキーによる操作を行えるようにする。
作成する機能
- 選択テキストによるDeepL英日翻訳(テキスト選択後、Ctrl+Shift+Lで起動)
- 選択テキストによる英Google検索(テキスト選択後、Ctrl+Shift+Eで起動)
全然関係無いが、Ctrl+EでChromeのアドレスバーに飛ぶので日Google検索はなし。
手順
- manifestにcontent_scriptsを追加する
- manifestにcommands(ショートカット定義)を追加する
- content.jsに選択テキストの変化に応じたbackground.jsへのメッセージ送信を追加する
- background.jsにメッセージ受信に応じた選択テキスト(グローバル変数)の更新を追加する
- 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}`);
});