Google Chrome ExtentionのStorage、Notification、Popupを使ってみた
はじめに
前回、Extentionアイコンに数字を表示するところまで実装しました。

今回はStorage、Notification、Popupの3機能を追加します。
Storage
過去の数値と比較して、変化があった場合に通知を送る機能を実装するためchrome.storage APIを使います。localStorageとの違いは、localStorageとの違い が分かりやすいです。
localStorageに比べて便利ですが、chrome.storageの場合は、保存と取得が非同期で処理されるため、その点だけ注意が必要です。
保存
chrome.storage.local.set({'identifier': identifier}, function(){
// hoge
});
取得
chrome.storage.local.get(['identifier'], function(storage) {
console.log(storage.identifier);
});
Notification

画面右上にこの通知を表示します。実装はこの1行でできます。
new Notification('Tip Receive Notification', {icon: 'images/icon_48.png', body: 'You received new tip. ' + object.result.count + ' Tips are not returned.'});
Popup

Popupを表示するにはpopup.htmlが必要です。background.jsとのデータ連携にはchrome.extension.getBackgroundPage()を利用します。Google Chrome拡張の作り方 に詳しく書かれています。
manifest.json
"browser_action": {
"default_icon": "images/icon_16.png",
"default_title": "Tip Monitor",
"default_popup": "popup.html"
},
popup.html
<script src="js/jquery.min.js"></script> <script src="js/popup.js"></script> <div> <input type="text" id="identifier" placeholder="Enter Your Identifier"> <input type="button" id="save" value="Save" /> </div>
popup.js
$(function(){
var backgroundPage = chrome.extension.getBackgroundPage();
$('#save').click(function(){
backgroundPage.saveIdentifier($('#identifier').val());
});
});
まとめ
次回はAngularJSの導入などやる予定です。ソースはgithubに置いてます。
参考
chrome.storageでchrome extension用のデータを保存・取得
Google Chrome拡張の作り方(その3:ポップアップ表示とバックグラウンドスクリプトとの連携)