message passing | chrome extension
http://code.google.com/chrome/extensions/messaging.html
サイトAのとき
http://a.com/
・backgroundから、サイトAにボタンを追加
・サイトAでボタンをクリックしたことをbackgroundで取得
content scriptに、クリックしてrequestするスクリプトを追加
http://code.google.com/chrome/extensions/content_scripts.html
manifest
“content_scripts”: [
{
“matches”: ["http://*.a.com/*"],
“js”: ["js/jquery-1.7.2.min.js","js/content.js"]
}
],
{
“matches”: ["http://*.a.com/*"],
“js”: ["js/jquery-1.7.2.min.js","js/content.js"]
}
],
js/content.js
var grCont = {};
grCont.doClick = function(){
// クリックしたらメセージを送る
chrome.extension.sendRequest({greeting: “hello”}, function(response) { console.log(response.farewell);});
};
$(document).ready(function(){
var url = location.href;
//ボタンを作る
$(‘body’).prepend(“click here“);
// ボタンに関数を
$(‘#myclick’).click(grCont.doClick);
});
grCont.doClick = function(){
// クリックしたらメセージを送る
chrome.extension.sendRequest({greeting: “hello”}, function(response) { console.log(response.farewell);});
};
$(document).ready(function(){
var url = location.href;
//ボタンを作る
$(‘body’).prepend(“click here“);
// ボタンに関数を
$(‘#myclick’).click(grCont.doClick);
});
background.js に イベントリスナーを入れる
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
console.log(‘onrequest’);
console.log(sender.tab ?
“from a content script:” + sender.tab.url :
“from the extension”);
if (request.greeting == “hello”)
sendResponse({farewell: “goodbye”});
});
function(request, sender, sendResponse) {
console.log(‘onrequest’);
console.log(sender.tab ?
“from a content script:” + sender.tab.url :
“from the extension”);
if (request.greeting == “hello”)
sendResponse({farewell: “goodbye”});
});
サンプルそのままですが。
これでページに埋めたリンクをクリックするとメッセージのやり取りが発生します。
開いているa.comでクリックするとconsoleにgoodbyeと。