我目前正在嘗試制作一個(gè) chrome 擴(kuò)展,在其彈出窗口中列出所有打開(kāi)的選項(xiàng)卡。稍后將添加更多功能,例如通過(guò)彈出窗口關(guān)閉特定選項(xiàng)卡,打開(kāi)具有特定 URL 的新選項(xiàng)卡等。清單文件{ "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ù)我的理解,因?yàn)槟鷳?yīng)該讓聽(tīng)眾參與background.js對(duì)標(biāo)簽的任何更改。然后當(dāng)這些發(fā)生時(shí),您可以發(fā)送消息到popup.js如您所見(jiàn),現(xiàn)在我只是嘗試在控制臺(tái)中記錄我的選項(xiàng)卡以確保其正常工作,然后再將其附加到 div 或我的popup.html. 但是,這不起作用,因?yàn)樵谖襭opup.html的控制臺(tái)中我收到以下錯(cuò)誤:popup.js:3 Uncaught TypeError: Cannot read property 'sendMessage' of undefined所以我......有點(diǎn)理解,由于某些限制,我不能在 popup.js 中使用 onMessage,但我也不知道如何實(shí)現(xiàn)我想要做的事情。
將數(shù)據(jù)(標(biāo)簽)從 background.js 傳遞到 popup.js
ibeautiful
2021-08-20 16:47:56