Chrome标签页查询返回空标签页数组 [英] Chrome tabs query returning empty tab array
问题描述
我正在尝试将已在Firefox中使用的Web扩展移植到chrome,但遇到一些问题.我需要从后台脚本向内容脚本发送消息.当我第一次从Firefox构建端口时,我使用的是端口,但是我将其切换为使用chrome.tabs.query()
,因为chrome一直发现错误.但是现在使用query()
,它在Firefox中仍然可以正常工作,但是现在chrome表示找不到当前选项卡:
I'm trying to port a Web Extension that I've gotten working in Firefox to chrome and I having some problems. I need to send a message form the background script to a content script. I was using a port when I first build it from Firefox, but I switched it to using chrome.tabs.query()
because chrome kept finding an error. But now with query()
, it still works fine in Firefox, but now chrome is saying that it can't find the current tab:
Error handling response: TypeError: Cannot read property 'id' of undefined
at chrome-extension://hhfioopideeaaehgbpehkmjjhghmaaha/DubedAniDL_background.js:169:11
它返回tab参数传递为length ==0.console.log(tabs)
:
It returns that the tab argument pass is length == 0. console.log(tabs)
:
[]
这是Chrome抱怨的功能.
This is the function that Chrome is complaining about.
var browser = chrome; // I set this only for compatibility with chrome; not set in Firefox.
function sendToTab(thing) {
browser.tabs.query(
{active: true, currentWindow: true},
function(tabs) {
console.log(tabs);
browser.tabs.sendMessage(
tabs[0].id, // The inspector identifies an error on this line
thing
);
}
);
}
该功能在Firefox中可以正常工作,并且可以访问选项卡.但这在Chrome中不起作用.
The same function works fine in Firefox and has no problem getting access to the tab. But it doesn't work in Chrome.
@wOxxOm:
显示调用sendToTab的代码
Show the code that calls sendToTab
这是sendToTab的调用位置:
This is where sendToTab is called:
function logURL(requestDetails) {
var l = requestDetails.url;
if (l.includes(test_url)) {
if (logOn) { console.log(l); }
sendToTab({dl_url: l});
}
}
browser.webRequest.onBeforeRequest.addListener(
logURL,
{urls: ["<all_urls>"]}
);
推荐答案
听起来像您在活动窗口是devtools时正在运行此代码,这是一个已知错误.
Sounds like you're running this code while your active window is devtools, which is a known bug.
您的代码中发生了另一个问题:即使请求可能是在后台(非活动)选项卡中发生的,它也始终会访问焦点(活动)选项卡.
Another problem takes place in your code: it always accesses the focused (active) tab even though the request may have occurred in a backgrounded (inactive) tab.
解决方案:
使用在侦听器函数参数中提供的标签ID作为
您的情况是requestDetails.tabId
Use the tab id provided inside the listener function parameter as tabId
property.
In your case it's requestDetails.tabId
如果出于任何原因您确实想要活动选项卡,请确保在运行此代码时一个真实的窗口处于活动状态,或者使用以下变通办法,即使集中了devtools窗口,该变通方法也会成功:
If for whatever reason you really want the active tab, make sure a real window is active while this code runs or use the following workaround that succeeds even if devtools window is focused:
chrome.windows.getCurrent(w => {
chrome.tabs.query({active: true, windowId: w.id}, tabs => {
const tabId = tabs[0].id;
// use tabId here...
});
});
这篇关于Chrome标签页查询返回空标签页数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!