Chrome 标签查询返回空标签数组

971*_*278 3 google-chrome-extension firefox-addon-webextensions

我正在尝试将我在 Firefox 中使用的 Web 扩展移植到 chrome,但我遇到了一些问题。我需要从后台脚本向内容脚本发送一条消息。当我第一次从 Firefox 构建它时,我正在使用一个端口,但我将其切换为使用,chrome.tabs.query()因为 chrome 不断发现错误。但是现在有了query(),它在 Firefox 中仍然可以正常工作,但是现在 chrome 说它找不到当前选项卡:

Error handling response: TypeError: Cannot read property 'id' of undefined
    at chrome-extension://hhfioopideeaaehgbpehkmjjhghmaaha/DubedAniDL_background.js:169:11
Run Code Online (Sandbox Code Playgroud)

它返回的标签参数通是长度== 0 console.log(tabs)

[]
Run Code Online (Sandbox Code Playgroud)

这是 Chrome 抱怨的功能。

Error handling response: TypeError: Cannot read property 'id' of undefined
    at chrome-extension://hhfioopideeaaehgbpehkmjjhghmaaha/DubedAniDL_background.js:169:11
Run Code Online (Sandbox Code Playgroud)

相同的功能在 Firefox 中运行良好,访问选项卡没有问题。但它在 Chrome 中不起作用。

更新 2020-01-30

@wOxxOm:

显示调用 sendToTab 的代码

这是调用 sendToTab 的地方:

[]
Run Code Online (Sandbox Code Playgroud)

wOx*_*xOm 5

听起来您正在运行此代码,而您的活动窗口是 devtools,这是一个已知错误

另一个问题发生在您的代码中:即使请求可能发生在后台(非活动)选项卡中,它也始终访问聚焦(活动)选项卡。

解决方案:

使用侦听器函数参数中提供的选项卡 ID作为tabId属性。
在你的情况下requestDetails.tabId

如果出于某种原因您确实需要活动选项卡,请确保在此代码运行时真实窗口处于活动状态,或者使用以下解决方法,即使 devtools 窗口已获得焦点也能成功:

chrome.windows.getCurrent(w => {
  chrome.tabs.query({active: true, windowId: w.id}, tabs => {
    const tabId = tabs[0].id;
    // use tabId here...
  });
});
Run Code Online (Sandbox Code Playgroud)