69

来自 popup.js 的消息被两次发布到 background.js,但我从 background.js 中一无所获。

背景.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");
  });
});

popup.js:

function login(){
alert(document.login.username.value);
chrome.extension.sendRequest({ msg: "login",username:document.login.username.value,password:document.login.password.value});
document.getElementById('openBackgroundWindow').visbility = "hidden";

}

$(document).ready(function (){

checkUserAuth();
console.log("Inside");
$("#openBackgroundWindow").click(login);

});


function checkUserAuth(){
console.log(localStorage.getItem("apiKey"));
if(localStorage.getItem("apiKey") != null)
    {
        $("#openBackgroundWindow").visbility ="hidden";
    }
}


var port = chrome.extension.connect({name: "Sample Communication"});
port.postMessage("Hi BackGround");
port.onMessage.addListener(function(msg) {
        console.log("message recieved"+ msg);
});
4

3 回答 3

127

方法 - A:
使用长寿命连接,您可以从 background.js 与任何活动的扩展页面的 popup.js 进行通信(这里我包含了 popup.html 和only initiated来自 popup.js 的示例通信作为示例)

背景.js

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

popup.js

 var port = chrome.extension.connect({
      name: "Sample Communication"
 });
 port.postMessage("Hi BackGround");
 port.onMessage.addListener(function(msg) {
      console.log("message recieved" + msg);
 });

Method - B :
Direct Manipulation of DOM* 如果你的最终结果是修改 DOM,你可以用这个来实现

popup.html

<html>
    <head>
        <script src="popup.js"></script>
    </head>
    <body>
        <div id="x" value="m">Some thing</div>
    </body>
</html>

背景.js

var views = chrome.extension.getViews({
    type: "popup"
});
for (var i = 0; i < views.length; i++) {
    views[i].document.getElementById('x').innerHTML = "My Custom Value";
}

方法 - C:

使用 Long Lived Connections,您可以从 background.js 与任何活动的扩展页面的 popup.js 进行通信(这里我没有包含 popup.html 并从 background.js 发起示例通信;

背景.js

chrome.browserAction.onClicked.addListener(function(tab) {

    var port = chrome.extension.connect({
        name: "Sample Communication"
    });
    port.postMessage("Hi BackGround");
    port.onMessage.addListener(function(msg) {
        console.log("message recieved" + msg);
    });

});

我已经更改了您的代码并在消除了一些内容并使其成为简单版本后使其运行。在这个骨架上添加你的 AJAX 请求和 HTML DOM 代码(确保你<script>在 head 部分添加标签并chrome.extension.onConnect.addListener放出(xhr.readyState == 4)代码;)

popup.html

<html >
    <head>
        <script src="popup.js"></script>
    </head>
    <body></body>
</html>

清单.json

{
    "name": "Demo",
    "version": "1.0",
    "manifest_version": 2,
    "description": "This is a demo",
    "browser_action": {
        "default_popup": "popup.html"
    },
    "background": {
        "scripts": ["background.js"]
    },
    "permissions": ["<all_urls>",
        "storage",
        "tabs"
    ]
}

背景.js

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

popup.js

var port = chrome.extension.connect({
    name: "Sample Communication"
});
port.postMessage("Hi BackGround");
port.onMessage.addListener(function(msg) {
    console.log("message recieved" + msg);
});
于 2012-11-25T07:47:05.450 回答
22

这可以用于2路通信。两个文件中都有相同的代码。

popup.js & background.js

//for sending a message
chrome.runtime.sendMessage({greeting: "hello"}, function(response) {

});

//for listening any message which comes from runtime
chrome.runtime.onMessage.addListener(messageReceived);

function messageReceived(msg) {
   // Do your work here
}

参考:https ://developer.chrome.com/extensions/runtime#method-sendMessage

于 2017-04-16T19:36:17.217 回答
3

全双工通信

background.js异步调用方法popup.js返回响应

Popup.js:

// wrapper method 
function getContent() {
    callEventPageMethod('getContent', 'some parameter', function (response) {
        doSomethingWith(response);
    });

}

//generic method
function callEventPageMethod(method, data, callback) {
    chrome.runtime.sendMessage({ method: method, data: data }, function (response) {
        if(typeof callback === "function") callback(response);
    });
}

背景.js/eventPage.js:

chrome.runtime.onMessage.addListener(callback);
function callback(obj, sender, sendResponse) {
    if (obj) {
        if (obj.method == 'getContent') {
            getContent(sendResponse);
        } else if (obj.method == 'othermethod') {

        }
    }
    return true; // remove this line to make the call sync!
}


//some async method
function getContent(sendResponse) {
    chrome.storage.local.get(["mydata"], function (obj) {
        var mydata = $.trim(obj["mydata"]);
        sendResponse(mydata);
    });
}

如果需要从background.js调用popup.js方法,则将上述代码交换到文件中。


方法二: 可以在变量中加载背景页面的引用,访问所有方法。

var bgPage = chrome.extension.getBackgroundPage();
 var response =  bgPage.someMethodInBGPage();
于 2017-11-29T05:23:37.503 回答