我目前正在嘗試制作一個 chrome 擴展,在其彈出窗口中列出所有打開的選項卡。稍后將添加更多功能,例如通過彈出窗口關閉特定選項卡,打開具有特定 URL 的新選項卡等。清單文件{ "manifest_version": 2, "name": "List your tabs!", "version": "1.0.0", "description": "This extension only lists all of your tabs, for now.", "background": { "persistent": true, "scripts": [ "js/background.js" ] }, "permissions": [ "contextMenus", "activeTab", "tabs" ], "browser_action": { "default_popup": "popup.html" }}背景.jsconst tabStorage = {};(function() { getTabs(); chrome.tabs.onRemoved.addListener((tab) => { getTabs(); }); chrome.tabs.onUpdated.addListener((tab) => { getTabs(); });}());function getTabs() { console.clear(); chrome.windows.getAll({populate:true},function(windows){ windows.forEach(function(window){ window.tabs.forEach(function(tab){ //collect all of the urls here, I will just log them instead tabStorage.tabUrl = tab.url; console.log(tabStorage.tabUrl); }); }); }); chrome.runtime.sendMessage({ msg: "current_tabs", data: { subject: "Tabs", content: tabStorage } });}彈出窗口.js(function() { chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) { if (request.msg === "current_tabs") { // To do something console.log(request.data.subject) console.log(request.data.content) } } );}());根據(jù)我的理解,因為您應該讓聽眾參與background.js對標簽的任何更改。然后當這些發(fā)生時,您可以發(fā)送消息到popup.js如您所見,現(xiàn)在我只是嘗試在控制臺中記錄我的選項卡以確保其正常工作,然后再將其附加到 div 或我的popup.html. 但是,這不起作用,因為在我popup.html的控制臺中我收到以下錯誤:popup.js:3 Uncaught TypeError: Cannot read property 'sendMessage' of undefined所以我......有點理解,由于某些限制,我不能在 popup.js 中使用 onMessage,但我也不知道如何實現(xiàn)我想要做的事情。
將數(shù)據(jù)(標簽)從 background.js 傳遞到 popup.js
ibeautiful
2021-08-20 16:47:56