客观的
当用户访问新网站时,我正在尝试获取活动标签的网址。chrome 网上商店建议我删除tabs
权限并activeTab
改用。我没有内容脚本,只需要活动 URL。
当前代码
我目前获得活动选项卡并将其保存到具有选项卡权限的全局变量中:
let ACTIVE_URL = '';
chrome.tabs.onActivated.addListener((_activeInfo)=> {
chrome.tabs.query({active: true}, (tabs) => {
ACTIVE_URL = tabs[0].url || tabs[0].pendingUrl || ACTIVE_URL;
});
});
chrome.tabs.onUpdated.addListener((_tabID, _changeInfo, tab) => {
ACTIVE_URL = tab.url || ACTIVE_URL;
});
医生说有可能吗?
这个问题,以及 woxxom 的评论似乎表明这是不可能的。但根据activeTab 文档,activeTab 允许您
使用 webRequest API 拦截选项卡中对选项卡主框架源的网络请求。扩展暂时获得选项卡主框架来源的主机权限。
所以看起来这是可能的(代替 placeholder chrome.getActiveUrl();
)。
chrome.webRequest.onBeforeRequest.addListener(
(webRequest) => {
const activeURL = ACTIVE_URL // chrome.getActiveUrl();
if (activeURL === url.im.looking.for) {
return {cancel: true};
}
return {cancel: false};
},
{
urls: ["http://*/*", "https://*/*"],
types: ['main_frame']
},
['blocking']
);
异步替代方案
这个问题说不可能在 onBeforeRequest 监听器中使用异步函数。
问题
如何在 webRequest 回调 fn 中获取带有 activeTab 的 URL?