extension getting started
CarsonSlovoka opened this issue · 3 comments
- chrome.i18n.getMessage不支援HTML,他只可以js, css, json之類的文件,找尋支援HTML的方法 #1 (comment)
- 一個實際的案例,包含兩種語言 (bc1c584)
This issue that teaches you to do the things as below,
- locale (#1 (comment))
- command (hotkey) (#1 (comment))
a7e828c
locale
可以參考: https://stackoverflow.com/a/68329931/9935654
manifest.json要先新增
"default_locale": "en"
接著新增_locales資料夾
- manifest.json
- 📂 _locales 👈
- 📂 en
- messages.json
- 📂 es
- messages.json
- 📂 ...
- messages.json
- messages.json 格式,基本上他只要求兩個東西
- name: 可以替換成你要的名稱
- message: 後面就是要呈現出來的訊息
{myName:{ // chrome.i18n.getMessage("myName")
"message": ""
}}
6f15779
commands (hotkey)
{
"name": "My extension",
"commands": {
"undo": { // 可以新增很多個指令,隨便你的名稱要用什麼
"suggested_key": { // 這裡的熱鍵是指當您的extension被喚起時,還可以在觸發其他的熱鍵
"default": "Alt+U"
},
"description": "" // 可有可無
},
"_execute_action": { // 這個名稱會做保留,使用此熱鍵,如同您直接點擊您的extension的動作
"suggested_key": {
"windows": "Ctrl+Shift+Y",
"mac": "Command+Shift+Y",
"chromeos": "Ctrl+Shift+U",
"linux": "Ctrl+Shift+J"
}
}
}
}
其中除了_execute_action外的熱鍵,都可以被監聽
chrome.commands.onCommand.addListener((cmdName) => {
switch (cmdName) {
case "show-alert":
chrome.storage.sync.set({msg})
chrome.tabs.query({active: true, currentWindow: true}).then(([tab])=>{
chrome.scripting.executeScript({
target: {tabId: tab.id},
function: () => {
chrome.storage.sync.get(['msg'], ({msg})=> {
console.log(`Command: ${msg}`)
alert(`Command: ${msg}`)
})
}
})
})
break
case "undo":
new Promise(resolve => {
resolve()
}).then()
break
default:
alert(`Unknown Command: ${cmdName}`)
}
})
❗ 注意 chrome.scripting.executeScript.function 沒辦法傳入參數,會抓不到參數的數值,原因請參考
This function will be executed in the context of injection target. However, this will not carry over any of the current execution context of the function. As such, bound parameters (including the this object) and externally-referenced variables will result in errors. For instance, the following code will not work, and will throw a ReferenceError because color is undefined when the function execute
You can work around this by using the Storage API or by passing messages.
所以我們用Storage去放置我們想要的訊息