manifest.json
{
"name": "communication between background.js and popup.js example",
"version": "1.0",
"description": "communication between background.js and popup.js",
"content_scripts": [{
"matches": ["<all_urls>"],
"js": ["content.js"]
}],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"browser_action": {
"default_title": "communicate with background",
"default_popup": "popup.html"
},
"permissions": [
"activeTab"
],
"manifest_version": 2
}popup.html
<p>I am popup.html</p> <button id="btn">hello</button><br> msg from background.js: <div id="div"></div> <script type="text/javascript" src="popup.js"></script>
popup.js
console.log("I am popup.js");
document.getElementById("btn").onclick = function(e){
hello();
}
function hello() {
console.log("hello");
chrome.runtime.sendMessage({
greeting: "hello"
},
function(response) {
document.getElementById("div").textContent = response.msg;
});
}background.js
console.log("I am background.js");
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.greeting == "hello")
sendResponse({
msg: "goodbye!"
});
});1) popup.htmlに設置されたhelloボタンをクリックすると、background.jsにリクエストが送信される。
2) background.jsがリクエストを受信したら、今度はpopup.jsに返答。
3) popup.jsで返答を受信したら、それをpopup.htmlに表示。
簡単ですね。
0 件のコメント:
コメントを投稿