この記事で取り上げているAPIは現在と使い方が異なっていたり,
特にToolstrips APIは最新のChromeでは使用できなくなっています。詳しくは
前回はExtensionsの作り方からドキュメント,
前回の復習とバグフィックス
前回作成したSBMカウンタは,
一つ目のバグは,
このとき,
onSelectionChangedのバグ修正
chrome.tabs.onSelectionChanged.addListener(function(tabid){
chrome.tabs.get(tabid, function(tab){
if (tab.windowId === current_window.id) {
run_on_tab(tab);
}
});
});
続いて,
onUpdatedのバグ修正
chrome.tabs.onUpdated.addListener(function(tabid, inf){
if (inf.status === 'loading') {
chrome.tabs.getSelected(current_window.id, function(tab){
if (tab.id === tabid) {
run_on_tab(tab, true);
} else {
run_on_tab(tab, false, true);
}
});
}
});
なお,
Page Actions と Background Pages
続いて,
Page Actionsの定義
"page_actions": [
{
"id": "hatena",
"name": "add hatena bookmark",
"icons": [
"hatena.favicon.gif"
]
},
{
"id": "delicious",
"name": "add delicious",
"icons": [
"delicious.small.gif"
]
}
],
idはそのpage_
続いて,
Background Pagesの定義
"background_page": "background.html",
では,
サービスの定義
var PageActionServices = [
{
"id":"hatena",
"title":"add hatena bookmark",
"url":"http://b.hatena.ne.jp/add?&url=#{encoded_url}&title=#{title}"
},
{
"id":"delicious",
"title":"add delicious",
"url":"http://delicious.com/save?v=5&jump=close&url=#{encoded_url}&title=#{title}"
}
];
このサービスの定義はToolstripsで使用している定義と共有する形にしてもよいのですが,
続いて,
enableForTabによるActionの登録
chrome.tabs.onUpdated.addListener(function(tabid, inf){
if (inf.status !== 'loading') return;
chrome.tabs.get(tabid, function(tab){
if (!/^http/.test(tab.url)) return;
PageActionServices.forEach(function(service){
var opt = {
tabId: tab.id,
url: tab.url,
title: service.title,
iconId: 0
};
chrome.pageActions.enableForTab(service.id, opt);
});
});
});
ここでもTabs APIのonUpdatedイベントでタブを取得し,
これでアドレスバー
enableForTabによるActionの登録
PageActionServices.forEach(function(service){
chrome.pageActions[service.id].addListener(function(id, tabinf){
if (!tabinf){//for Chrom 3
tabinf = id.data;
id = id.pageActionId;
}
chrome.tabs.get(tabinf.tabId,function(tab){
var inf = {
encoded_url:encodeURIComponent(tab.url),
title:tab.title
};
var opt = {
url: fill(service.url, inf),
selected: true
};
chrome.tabs.update(tab.id,opt);
});
});
});
function fill(str, opt){
function replacer(_, _$){
return opt[_$] || '';
}
return str.replace(/#\{([^}]+)\}/g, replacer);
}
chrome.
あとはタブIDからTabオブジェクトを取得し,