猿问

将数据(标签)从 background.js 传递到 popup.js

我目前正在尝试制作一个 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"

  }

}

背景.js


const 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)

            }

        }

    );


}());

根据我的理解,因为您应该让听众参与background.js对标签的任何更改。然后当这些发生时,您可以发送消息到popup.js


如您所见,现在我只是尝试在控制台中记录我的选项卡以确保其正常工作,然后再将其附加到 div 或我的popup.html. 但是,这不起作用,因为在我popup.html的控制台中我收到以下错误:


popup.js:3 Uncaught TypeError: Cannot read property 'sendMessage' of undefined


所以我......有点理解,由于某些限制,我不能在 popup.js 中使用 onMessage,但我也不知道如何实现我想要做的事情。


ibeautiful
浏览 408回答 1
1回答
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答