来自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");
});
});
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);
});
答案 0 :(得分:90)
方法 - 答:
使用Long Lived Connections 您可以从background.js与扩展页面的popup.js进行通信对于任何活动(这里我已经将popup.js中的popup.html和only initiated
示例通信作为示例包含在内)
<强> background.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);
});
方法 - B:
直接操作DOM *如果您的最终结果是修改DOM,您可以用此实现
<强> popup.html 强>
<html>
<head>
<script src="popup.js"></script>
</head>
<body>
<div id="x" value="m">Some thing</div>
</body>
</html>
<强> background.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启动了示例通信; < / p>
<强> background.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的代码(确保在head部分添加<script>
标记,并将chrome.extension.onConnect.addListener
放在(xhr.readyState == 4)
代码之外;)
<强> popup.html 强>
<html >
<head>
<script src="popup.js"></script>
</head>
<body></body>
</html>
<强> 的manifest.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"
]
}
<强> background.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);
});
答案 1 :(得分:13)
这可以用于双向通信。两个文件都有相同的代码。
popup.js&amp; 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
答案 2 :(得分: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);
});
}
Background.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 方法,请在文件中交换上述代码。
方法2: 您可以在变量中加载背景页面的引用并访问所有方法。
var bgPage = chrome.extension.getBackgroundPage();
var response = bgPage.someMethodInBGPage();