javascript - 检测 Tab 重复事件

标签 javascript google-chrome google-chrome-extension dom-events chromium

我正在开发 Chrome 扩展;

我需要检测标签何时被复制,我正在寻找类似 onduplicate.addListener() 的标签检测事件?

Chrome 扩展程序 API 可以做到这一点吗?

最佳答案

这是最接近的实现:

const newTabsId = new Set();

// Observe all new tabs with opener ID
chrome.tabs.onCreated.addListener(tab => {
    if(tab.openerTabId) {
        newTabsId.add(tab.id);
    }
});

// Waiting for a new tab completeness
chrome.tabs.onUpdated.addListener((tabId, changes, tab) => {
    if(newTabsId.has(tabId) && changes.status === 'complete') { 
        if(!tab.openerTabId) {
            return;
        }
        // Retrieve opener (original) tab
        getTabById(tab.openerTabId)
            .then(originalTab => {
                if(
                    originalTab.url === tab.url &&          // original and new tab should have same URL
                    originalTab.index + 1 === tab.index &&  // new tab should have next index
                    tab.active && tab.selected              // new tab should be active and selected
                                                            // also we may compare scroll from top, but for that we need to use content-script
                ) {
                    console.log('Duplicate:', tab);
                }
            });
        // Remove this tab from observable list
        newTabsId.delete(tabId);
    }
});

// Syntax sugar
function getTabById(id) {
    return new Promise((resolve, reject) => {
        chrome.tabs.get(id, resolve);
    });
}

// Cleanup memory: remove from observables if tab has been closed
chrome.tabs.onRemoved.addListener(tabId => {
    newTabsId.delete(tabId);
});

编辑 1:但是,是的,现在没有明确的解决方案来检测真正的重复

关于javascript - 检测 Tab 重复事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44236472/

相关文章:

javascript - 粗箭头函数抛出错误 "expression expected"

php - 使用 HTML 单选按钮和 javascript 进行评级

google-chrome - Google Chrome 中的 Bootstrap 复选框和单选按钮标签问题

javascript - 内容脚本在 Chrome 扩展中不起作用

javascript - Chrome 扩展代码 vs 内容脚本 vs 注入(inject)脚本

javascript - 将 json 保存到 chrome 存储/本地存储

javascript - 如何处理 AmCharts Stock 图表上的点击事件?

javascript - AngularJS 将 window.location 发送到函数或指令

html - Chrome 另存为 PDF 更改 CJK 字符

google-chrome - Chrome Adob​​e Flash 已过时