動態更改 Chrome Extension 中小圖示的標題


在 manifest.json 中的 browser_action 有一個鍵值是 default_title
這個值主要是用來設置,當滑鼠停留於 Chrome 的右方 Extension 小圖示上,出現的標題
如果想要動態更改他預設的文字,可以通過來更改

1
chrome.browserAction.setTitle({ title: "xxxx" });

比如想於標題中顯示 Extension 的版本可以用以下的方法.
這也是如何在 Extension 中讀取 manifest.json 內容的方法
將這程式碼放到 background.html 中就可以了

1
2
3
4
5
6
7
8
9
10
11
function get_version() {
var version = 'NaN';
var xhr = new XMLHttpRequest();
xhr.open('GET', chrome.extension.getURL('manifest.json'), false);
xhr.send(null);
var manifest = JSON.parse(xhr.responseText);
return manifest.version;
}
chrome.browserAction.setTitle({
title: "This is a title, version " + get_version()
});