![](/img/trans.png)
[英]How to avoid input keyboard shortcut stealing by websites in chrome extension develpment
[英]How to activate/deactivate chrome extension with keyboard shortcut (development)
我正在嘗試設置鍵盤快捷鍵來激活/停用我正在開發的 Chrome 擴展程序。 Chrome 擴展程序僅包含在某些站點上運行的“content_script”。 我希望它完全激活/停用擴展程序,就像我要通過 Chrome://extensions 禁用它一樣。
在我尋找答案的過程中,我看到了很多建議將“_execute_browser_action”添加到我的 manifest.json,但我認為這個命令需要一個需要在 background.js 中設置的監聽器(如果我錯了,請糾正我) . 如果可能的話,我想避免使用 background.js,因為我想讓這個擴展保持簡短和甜蜜。
這是我的清單。json:
{
"manifest_version": 2,
"name": "foo",
"description": "foo",
"version": "0.1.0",
"commands": {
"_execute_browser_action": {
"suggested_key": {
"default": "Ctrl+Shift+8"
}
}
},
"content_scripts": [{
"js": ["./dist/bundle.js"],
"matches": [ ...certain sites... ]
}],
"icons": {
"16": "/icons/logo16.png",
"32": "/icons/logo32.png",
"48": "/icons/logo48.png",
"128": "/icons/logo128.png"
}
}
使用此 manifest.json,快捷方式會顯示在 Chrome://extensions/shortcuts 中,但該快捷方式不執行任何操作。 當我按下組合時,沒有任何反應。 即使我刷新頁面、重新加載擴展程序、重新捆綁、重新啟動 Chrome 等。
我應該如何 go 關於添加此鍵盤快捷鍵?
另外,如果有幫助,我正在使用 Babel/Webpack。
我最終解決了我自己的問題。 在這里更新以防它幫助其他人。
事實證明 background.js 正是我想要的。 我的后台腳本設置了一個 chrome.storage API 字段,由 browserAction 觸發,然后我的 content_script 攝取該字段以打開/關閉它。 然后刷新頁面,更新頁面html。 (靈感來自這里)
背景.js:
var x = true
enableBrowserAction()
function disableBrowserAction() {
chrome.storage.local.set({enabled: false})
}
function enableBrowserAction() {
chrome.storage.local.set({enabled: true})
}
function updateState() {
if (x == false) {
x = true
enableBrowserAction()
} else {
x = false
disableBrowserAction()
}
chrome.tabs.reload()
}
chrome.browserAction.onClicked.addListener(updateState)
manifest.json(只有必要的字段):
{
"manifest_version": 2,
"browser_action": {},
"commands": {
"_execute_browser_action": {
"suggested_key": {
"default": "Ctrl+Shift+8"
}
}
},
"permissions": [
"storage"
],
"background": {
"scripts": ["background.js"]
},
"content_scripts": [{
"js": ["./dist/bundle.js"],
"matches": [ ...certain sites... ]
}]
}
content_script(bundle.js 的條目):
import ServiceHandler from './ServiceHandler.js'
chrome.storage.local.get('enabled', data => {
if (data.enabled) {
const sh = new ServiceHandler()
sh.execute()
}
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.