Message passing:
chrome.extension.onConnect.addListener(function(port) {
console.assert(port.name == "knockknock");
port.onMessage.addListener(function(msg) {
if (msg.joke == "Knock knock")
port.postMessage({question: "Who's there?"});
else if (msg.answer == "Madame")
port.postMessage({question: "Madame who?"});
else if (msg.answer == "Madame... Bovary")
port.postMessage({question: "I don't get it."});
});
});
これは私の background.js です:
function login(username,password){
console.log(username);
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:3000/login/", true);
xhr.setRequestHeader('Content-type','application/json; charset=utf-8');
data = {"username":username,"password":password};
console.log(JSON.stringify(data));
xhr.send(JSON.stringify(data));
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
// JSON.parse does not evaluate the attacker's scripts.
var resp = JSON.parse(xhr.responseText);
console.log(resp);
var lStorage = localStorage;
localStorage.setItem("username",resp["username"]);
localStorage.setItem("apiKey",resp["apiKey"]);
localStorage.setItem("password",resp["password"]);
console.log(localStorage.getItem("username"));
}
};
}
では、XHR.onReadyState から chrome.extension.onConnect.addListener(function(port) {} を呼び出して、background.js が受け取った値を popup.js に送信するにはどうすればよいでしょうか。
XHR.onReadyRequest 内で chrome.extension.onConnect.addListener(function(port) {} を定義できないことはわかっています。したがって、API 応答を受け取ったらメッセージを投稿するにはどうすればよいですか?