使用 Browser Action 的練習
- 可以輸入花費
- 顯示總計的花費
- 當超出預算時,彈跳通知訊息
- 有選項可以重置計算與設定上限
建立 manifest.json
{
"manifest_version" :2,
"name" : "Budget Manager",
"version" : "1.0",
"description" : "",
"icons" :{
"128" : "icon128.png",
"48" : "icon48.png",
"16" : "icon16.png"
},
"browser_action" :{
"default_icon" :"icon16.png",
"default_popup" : "popup.html"
}
}
建立 popup.html
<!DOCTYPE html>
<html>
<head>
<title>Budget Manager</title>
</head>
<body>
<h1>Budget Manager</h1>
<h2>Total Spend: <span id="total">0</span></h2>
<h2>Limit : <span id="limit"></span> </h2>
<input type="text" id="amount" />
<input type="submit" id="spendAmount" value="spend" />
</body>
</html>
掛載後應該會如下顯示

使用 Chrome Storage 需要再 manifest.json 裡面增加
"permissions" : [
"storage"
]

然後在 js 部分 使用
- chrome.storage.sync.get(‘variable name‘,function(…){});
- chrome.storage.sync.set({‘variable name‘ : value });
下載 jquery 並放到 script 部分(不能使用 CDN)
在 html 裡面增加 script 部分,命名為 popup.js

popup.js 部分
$(function(){
//如果 Chrome Storage 裡面有值的話 直接帶出
chrome.storage.sync.get('total',function(budget){
if(budget.total){
$('#total').text(budget.total);
}
});
//按鈕觸發後
$('#spendAmount').click(function(){
//取值
chrome.storage.sync.get('total',function(budget){
var newtotal = 0;
if(budget.total){
newtotal += parseInt(budget.total);
}
//更新值
var amount = $('#amount').val();
if(amount)
{
newtotal += parseInt(amount);
}
chrome.storage.sync.set({'total':newtotal});
//更新頁面
$('#total').text(newtotal);
$('#amount').val('');
})
})
})
執行結果 :

