问题描述
我正在尝试将我在 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参数pass是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 的代码
这是调用 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 函数参数作为 tabId
属性.
在您的情况下,它是 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 标签查询返回空标签数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!