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"]
}
],

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);
});

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”});
});

サンプルそのままですが。
これでページに埋めたリンクをクリックするとメッセージのやり取りが発生します。
開いているa.comでクリックするとconsoleにgoodbyeと。

This entry was posted on 水曜日, 4月 4th, 2012 at 9:42 PM and is filed under Chrome Extention. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

Unityによるゲームを公開しております iOS/Android
https://itunes.apple.com/jp/app/lost-knight-3d-action/id900917032
https://play.google.com/store/apps/details?id=com.groundroad.runknight

各種開発支援・機能開発等小さいお仕事などもお請けしております。
unity開発支援, PHPシステム開発, javascript/html5 フロント開発, titanium mobileアプリ開発
お気軽にお問い合わせください
大崎・五反田近郊での対面でのお打ち合わせはいつでも可能です。