简体   繁体   English

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

[英]Passing data (tabs) from background.js to popup.js

I am currently trying to make a chrome extension that lists all of the open tabs in its popup window. 我目前正在尝试制作一个Chrome扩展程序,该扩展程序在其弹出窗口中列出所有打开的标签页。 With more functionality to be added later, such as closing a specific tab through the popup, opening up a new tab with a specific URL etc. 稍后将添加更多功能,例如通过弹出窗口关闭特定标签,使用特定URL打开新标签等。

manifest.json 的manifest.json

{
  "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"
  }
}

background.js background.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
        }
    });
}

popup.js popup.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)
            }
        }
    );

}());

From my understanding, since you're supposed to have listeners in background.js for any changes to your tabs. 根据我的理解,由于您应该在background.js使用侦听器来更改选项卡。 Then when those occur, you can send a message to popup.js 然后,当发生这些情况时,您可以将消息发送到popup.js

As you can see, for now I'm simply trying to log my tabs in the console to make sure it works, before appending it to a div or something in my popup.html . 如您所见,在将其附加到div或popup.html某些内容之前,现在我只是尝试在控制台中登录我的标签以确保其正常工作。 This does not work, however, because in my popup.html I'm getting the following error in the console: 但是,这不起作用,因为在我的popup.html中,控制台中出现以下错误:

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

so I'm... kind of understanding that I can't use onMessage in popup.js due to certain restrictions, but I also have no clue, then, on how to achieve what I'm trying to do. 所以我……由于某种限制,我不能在popup.js中使用onMessage,但是我也对如何实现我想做的事情一无所知。

Any help would be appreciated. 任何帮助,将不胜感激。

  1. The Google's documentation about the background script is a bit vague. Google关于后台脚本的文档有点模糊。 The important thing for your use case is that the popup runs only when it's shown, it doesn't run when hidden, so you don't need background.js at all, just put everything in popup.js which will run every time your popup is shown, here's your popup.html: 对于您的用例而言,重要的是,弹出窗口仅在显示时才运行,而在隐藏时不运行,因此您根本不需要background.js,只需将所有内容都放入popup.js中即可在您每次运行时运行显示弹出窗口,这是您的popup.html:

     <script src="popup.js"></script> 
  2. The error message implies you were opening the html file directly from disk as a file:// page, but it should be opened by clicking the extension icon or via its own URL chrome-extension://id/popup.html where id is your extension's id. 该错误消息表示您是直接从磁盘上以file://页的形式打开html文件,但应通过单击扩展图标或通过其自己的URL chrome-extension://id/popup.html来打开它,其中id为您的扩展程序的ID。 This happens automatically when you click the extension icon - the popup is a separate page with that URL, with its own DOM, document , window , and so on. 单击扩展名图标时,此操作自动发生-弹出窗口是具有该URL的单独页面,并具有其自己的DOM, documentwindow等。

  3. The popup has its own devtools, see this answer that shows how to invoke it (in Chrome it's by right-clicking inside the popup, then clicking "inspect"). 弹出窗口有其自己的devtools,请参见此答案 ,其中显示了如何调用它(在Chrome中,通过右键单击弹出窗口内部,然后单击“检查”)。

  4. Extension API is asynchronous so the callbacks run at a later point in the future, after the outer code has already completed, which is why you can't use tabStorage outside the callback like you do currently. 扩展API是异步的,因此回调将在外部代码完成后在以后的某个时间运行,这就是为什么您不能像现在这样在回调之外使用tabStorage原因。 More info: Why is my variable unaltered after I modify it inside of a function? 更多信息: 在函数内部修改变量后,为什么变量未更改? - Asynchronous code reference . -异步代码参考

  5. There should be no need to enumerate all the tabs in onRemoved and onUpdated because it may be really slow when there's a hundred of tabs open. 无需枚举onRemoved和onUpdated中的所有选项卡,因为当打开一百个选项卡时,它可能真的很慢。 Instead you can modify your tabStorage using the parameters provided to the listeners of these events, see the documentation for details. 相反,您可以使用提供给这些事件的侦听器的参数来修改tabStorage,有关详细信息,请参阅文档 That requires tabStorage to hold the id of each tab so it would make sense to simply keep the entire response from the API as is. 这需要tabStorage保留每个标签的ID,因此仅保留来自API的整个响应是有意义的。 Here's a simplified example: 这是一个简化的示例:

     let allTabs = []; chrome.tabs.query({}, tabs => { allTabs = tabs; displayTabs(); }); function displayTabs() { document.body.appendChild(document.createElement('ul')) .append(...allTabs.map(createTabElement)); } function createTabElement(tab) { const el = document.createElement('li'); el.textContent = tab.id + ': ' + tab.url; return el; } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将价值从popup.js传递到background.js - How to deliver value from popup.js to background.js 将变量从popup.js传递到background.js,未定义 - Passing variable from popup.js to background.js received as undefined 如何在popup.js和background.js之间传递正确的消息? - How to do correct message passing between popup.js and background.js? 持续在setInterval中将消息从background.js发送到popup.js,但仅在打开弹出窗口时才发送? - Continually send message from background.js to popup.js in setInterval but only when popup is opened? popup.js和background.js之间的通信 - Communication between popup.js and background.js background.js和popup.js之间的通信 - Communication between background.js and popup.js 将带有选中复选框 ID 的消息从 popup.js 发送到 background.js - Send message with ID of checked checkbox from popup.js to background.js Chrome扩展程序:单击popup.js即可激活并执行background.js - Chrome extension: Activate and execute background.js on click from popup.js 在Chrome扩展程序中将变量从popup.js发送到background.js - Send a variable from popup.js to background.js in Chrome Extension 刷新background.js与popup.js的信息 - 谷歌浏览器扩展 - Refreshing background.js with info from popup.js - Google Chrome Extension
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM