如何在 Firefox 的 Web 扩展中获取当前选项卡的历史记录?
How to get the current tab's history in a Web Extension in Firefox?
是否有 API 可以在 Firefox 的 Web 扩展中获取当前选项卡的历史记录?就像单击并按住“后退”按钮一样,将出现一个下拉菜单以显示当前选项卡的历史记录。
没有。默认情况下,您无法请求某个选项卡的列表。
但是,您可以监听选项卡事件 onUpdated、onCreated 等。使用保持不变的 tabId,您可以在后台脚本 (background.js) 中保留一个 URL 列表,它始终是 运行 如果启用了插件。
你会这样做:
let arr=[]; // At the top of background.js
browser.tabs.onCreated.addListener(handleCreated); // Somewhere in background.js
function handleCreated(tab) {
let tabId = tab.id;
if(arr[tabId]==null) arr[tabId] = [];
arr[tabId].push(url);
}
function getHistoryForCurrentTab(){
function currentTabs(tabs) {
// browser.tabs.query returns an array, lets assume the first one (it's safe to assume)
let tab = tabs[0];
// tab.url requires the `tabs` permission (manifest.json)
// We will now log the tab history to the console.
for(let url of arr[tab.id]){
console.log(url);
}
}
function onError(error) {
console.log(`This should not happen: ${error}`);
}
browser.tabs.query({currentWindow: true, active: true}).then(currentTabs, onError);
}
以上代码是概念验证。您需要考虑一些改进:实施 onClosed 重置该 ID 的选项卡历史记录 (arr[tabId] = null),实施 onUpdated(肯定需要,与 handleCreated 中的逻辑相同)。
链接:
是否有 API 可以在 Firefox 的 Web 扩展中获取当前选项卡的历史记录?就像单击并按住“后退”按钮一样,将出现一个下拉菜单以显示当前选项卡的历史记录。
没有。默认情况下,您无法请求某个选项卡的列表。
但是,您可以监听选项卡事件 onUpdated、onCreated 等。使用保持不变的 tabId,您可以在后台脚本 (background.js) 中保留一个 URL 列表,它始终是 运行 如果启用了插件。
你会这样做:
let arr=[]; // At the top of background.js
browser.tabs.onCreated.addListener(handleCreated); // Somewhere in background.js
function handleCreated(tab) {
let tabId = tab.id;
if(arr[tabId]==null) arr[tabId] = [];
arr[tabId].push(url);
}
function getHistoryForCurrentTab(){
function currentTabs(tabs) {
// browser.tabs.query returns an array, lets assume the first one (it's safe to assume)
let tab = tabs[0];
// tab.url requires the `tabs` permission (manifest.json)
// We will now log the tab history to the console.
for(let url of arr[tab.id]){
console.log(url);
}
}
function onError(error) {
console.log(`This should not happen: ${error}`);
}
browser.tabs.query({currentWindow: true, active: true}).then(currentTabs, onError);
}
以上代码是概念验证。您需要考虑一些改进:实施 onClosed 重置该 ID 的选项卡历史记录 (arr[tabId] = null),实施 onUpdated(肯定需要,与 handleCreated 中的逻辑相同)。
链接: