Skip to content

Instantly share code, notes, and snippets.

@BcRikko
Created June 26, 2015 09:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BcRikko/45bc7acaa3df9a11240b to your computer and use it in GitHub Desktop.
Save BcRikko/45bc7acaa3df9a11240b to your computer and use it in GitHub Desktop.
Chrome Extensions send message from content scripts to background. -> http://kuroeveryday.blogspot.jp/2015/06/ChromeExtensionssendMessage.html
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
switch (request.type) {
case 'add':
add(request.value, sendResponse);
break;
case 'search':
search(request.value, sendResponse);
break;
default:
console.log('typeがわかんないよ');
console.log(request);
break;
}
}
);
function add(value, callback) {
// ここで登録処理
console.log('background:add_' + value);
callback("add:" + value);
}
function search(value, callback) {
// ここで検索処理
console.log('background:search_' + value);
callback("search:" + value);
}
var title = document.getElementsByClassName('post-title entry-title')[0].innerText;
chrome.runtime.sendMessage(
{
type: "add",
value: title
},
function (response) {
if (response) {
alert(response);
}
}
);
chrome.runtime.sendMessage(
{
type: "search",
value: title
},
function (response) {
if (response) {
alert(response);
}
}
);
{
"name": "ContentScriptとBackgroundの通信テスト",
"version": "0.0.1",
"manifest_version": 2,
"description": "ContentScriptとBackgroundをsendMessegaやonMessegeで通信できるか確認する",
"background": {
"scripts": ["./background.js"]
},
"content_scripts": [
{
"matches": ["http://kuroeveryday.blogspot.jp/*"],
"js": ["./content_script.js"]
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment