如何在 chrome 扩展中实现 popup.js 和 backound.js 之间的通信?

来自 popup.js 的消息被两次发送到 backound.js,但是我从 backound.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);
});
63388 次浏览

方法-A: < br/> 使用长期连接你可以从 backound.js 通信到任何活动的扩展页面的 popup.js (在这里我包含了 popup.html 和来自 popup.js 的 only initiated样例通信作为示例)

背景 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: < br/> 直接操作 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 ,您可以从 backound.js 与任何活动的扩展页面的 popup.js 进行通信(在这里,我没有包含 popup.html,而是从 backound.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 请求和 HTMLDOM 的代码(确保在头部添加 <script>标签,并将 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);
});

这可以用于双向通信。相同的代码进入两个文件。

Popup.js & backound.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

全双工通信

popup.js异步调用 background.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);
});
}

如果需要从 背景 Js调用 Popup.js方法,则在文件中交换上述代码。


方法二: 可以在变量中加载后台页的引用并访问所有方法。

var bgPage = chrome.extension.getBackgroundPage();
var response =  bgPage.someMethodInBGPage();

我从答案中得到的理解是: The problem is that if bg.js is trying to communicate with Popup.js, if it is not active it will return error that "no suitable endpoint".

因此,可以执行下列任一操作。

  1. STORAGE-使用 chrome STORAGE 临时保存共享消息
  2. DOM MANIPULATION-将消息永久保存在 DOM 本身(如果希望操作 DOM)中作为最终结果。
  3. 长期连接-创建一个长期连接与弹出窗口。(使用 chrome onConnect 方法)
  4. 全双工-使用握手方法通过双方的函数调用和使用响应回调来传递答案。

清单版本3

将消息从 popup.js 发送到 backound.js 的示例:

Json:

{
"name": "Getting Started Example",
"description": "Build an Extension!",
"version": "1.0",
"manifest_version": 3,
"action": {
"default_popup": "./popup.html"
},
"background": {
"service_worker": "./background.js"
}
}

图片来源:

<html>
<head>
<title>Title</title>
</head>
<body>
<button id="btn">Trigger BG</button>
<script src="popup.js"></script>
</body>
</html>

Popup.js:

document.getElementById('btn').addEventListener('click', () => {
// how we send data:
chrome.runtime.sendMessage({ greeting: 'hello' });
});

背景介绍:

// how we receive data:
chrome.runtime.onMessage.addListener((msg, sender, res) => {
console.log(msg);
});

您可以交换 popup 文件和后台 js 文件的内容,将数据从 backound.js 发送到 popup.js

医生: 信息传递Chrome 运行时