Created
June 26, 2015 09:45
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"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