我有一个带有background.js和content.js的Chrome扩展程序。 content.js将消息发送到background.js有两次不同的时间。
[当前,当我从content.js发送第一个请求时,它同时到达了background.js中的两个侦听器。如何告诉请求仅转到所需的后台脚本(因此articleUrl转到第一个侦听器,articleData转到第二个侦听器?)
content.js
chrome.runtime.sendMessage({ "articleUrl": articleUrl }, function (response) {
console.log("sending articleUrl");
console.log(response);
});
button.addEventListener("click", function () {
chrome.runtime.sendMessage({ "title": title, "image_url": image, "url": url, "snippet": "test" }, function (response) {
console.log("sending articleData");
console.log(response);
});
});
background.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
console.log("receiving articleUrl");
console.log(request);
});
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
console.log("recieving articleData");
console.log(request);
});
仅设置一个消息侦听器,并根据消息的类型将数据定向到适当的功能。类似于:
content.js
chrome.runtime.sendMessage({ "type": "articleUrl", "articleUrl": articleUrl }, function (response) {
console.log("sending articleUrl");
console.log(response);
});
button.addEventListener("click", function () {
chrome.runtime.sendMessage({ "type": "articleData", "title": title, "image_url": image, "url": url, "snippet": "test" }, function (response) {
console.log("sending articleData");
console.log(response);
});
});
background.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.type == "articleUrl") {
// Handle articleUrl
}
else if (request.type == "articleData") {
// Handle articleData
}
});