0
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:如何在鉻擴展中從XHR.OnReadyState中發佈消息?
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"));
}
};
}
所以,我怎麼叫chrome.extension.onConnect.addListener(功能(端口){}從XHR.onReadyState這樣我就可以發送值popup.js曾經被background.js收到
我知道我無法在XHR.onReadyRequest中定義chrome.extension.onConnect.addListener(function(port){}。因此,如何發佈消息一旦我收到API響應?