相关疑难解决方法(0)

如何在chrome扩展中的popup.js和background.js之间进行通信?

来自popup.js的消息被发送两次到background.js,但我从background.js中得到的一切都没有.

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"));



  }
};


}


chrome.extension.onRequest.addListener(
    function(request, sender, sendResponse){
        console.log("hello");
        if(request.msg == "login") {
            //alert(request.password);
            login(request.username,request.password);}
    }
);

  chrome.extension.onConnect.addListener(function(port) {
  console.log("Connected .....");
  port.onMessage.addListener(function(msg) {
        console.log("message recieved "+ msg);
        port.postMessage("Hi Popup.js");
  });
}); …
Run Code Online (Sandbox Code Playgroud)

javascript google-chrome-extension

42
推荐指数
2
解决办法
4万
查看次数