[英]Chrome.runtime.onMessage.addListener on new tab not receiving message from popup.js
I have the following code in popup.js which responds to a button press to get all the tabs, create a new tab (template.html), and send the tabs as an array to the new tab. 我在popup.js中有以下代码,该代码响应按下按钮来获取所有选项卡,创建一个新选项卡(template.html),并将这些选项卡作为数组发送到新选项卡。 Later I will delete the current tabs and display the links on one page to save space (That's the idea of the extension).
稍后,我将删除当前选项卡,并在一页上显示链接以节省空间(这就是扩展的想法)。
function saveAll() {
var openTabs = [];
chrome.tabs.query({}, function(tabs) {
for (var i = 0; i < tabs.length; i++) {
openTabs[i] = tabs[i];
}
createSavedPage(openTabs);
});
}
function createSavedPage(tabsToSave) {
chrome.tabs.create({
"url": chrome.extension.getURL("template.html"),
"active": false
},
function(tab) {
sendListToPage(tab, tabsToSave);
}
);
}
function sendListToPage(tab, tabsArray) {
chrome.tabs.sendMessage(tab.id, {
"action": "fill-list",
"data": tabsArray
});
}
var saveAllButton = document.getElementById("select-all-tabs");
saveAllButton.addEventListener("click", saveAll);
The tab that is created includes a template.js file: 创建的选项卡包括template.js文件:
function fillList(array) {
var list = document.getElementById("link-list");
for (var item in array) {
//Something
}
}
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.action == "fill-list") {
var data = request.data;
fillList(data);
}
}
);
When I create the new tab, the message is sent from the extension but never received. 当我创建新标签时,邮件是从扩展名发送的,但从未收到。 What is causing this issue?
是什么导致此问题?
I also thought that the message was being sent before the created tab was fully loaded. 我还认为在创建的选项卡完全加载之前就已发送了消息。 So I've changed popup.js by adding a chrome.tabs.onUpdated listener:
因此,我通过添加chrome.tabs.onUpdated侦听器来更改popup.js:
function createSavedPage(tabsToSave) { chrome.tabs.create({ "url": chrome.extension.getURL("template.html"), "active": false }, function(tab) { chrome.tabs.onUpdated.addListener(function(tabId, info) { if (tabId == tab.id && info.status == "complete") sendListToPage(tab, tabsToSave); }); } ); }
And it seems to solve the issue. 而且似乎可以解决问题。 Is there still a better way?
还有更好的方法吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.