how to get current tabId from background page

后端 未结 4 1080
轮回少年
轮回少年 2020-12-14 15:02

how to get current tabId from background page? current tabId is the tab that user can see its content.

background.html



             


        
相关标签:
4条回答
  • 2020-12-14 15:19

    Run this in your background page

    chrome.tabs.query({active:true,windowType:"normal", currentWindow: true},function(d){console.debug(d);})
    

    or even better

    chrome.tabs.query({active:true,windowType:"normal", currentWindow: true},function(d){console.debug(d[0].id);})
    
    0 讨论(0)
  • 2020-12-14 15:27

    getSelected has been deprecated. The new way to do it is:

    chrome.tabs.query(
      {currentWindow: true, active : true},
      function(tabArray){...}
    )
    

    If you want to perform some callback on the active tab, you can wrap the above as so:

    function doInCurrentTab(tabCallback) {
        chrome.tabs.query(
            { currentWindow: true, active: true },
            function (tabArray) { tabCallback(tabArray[0]); }
        );
    }
    

    For example

    var activeTabId;
    doInCurrentTab( function(tab){ activeTabId = tab.id } );
    
    0 讨论(0)
  • 2020-12-14 15:33

    Many API methods interpret null as a current tab. chrome.tabs.sendRequest is one of them.

    Otherwise:

    chrome.tabs.getSelected(null, function(tab) { ... })
    
    0 讨论(0)
  • 2020-12-14 15:39

    If you have tabs user permission, the query method is this: chrome.tabs.query


    getCurrentWindowActiveTabIndex().then(tabIndex => {
        // do something
    });
    
    // asnyc getter, not just a regular 'thunk'
    function getCurrentWindowActiveTabIndex () {
        return new Promise((resolve, reject) => {
            chrome.tabs.query({
                currentWindow: true,
                active: true,
            }, (currentWindowActiveTabs = []) => {
                if (!currentWindowActiveTabs.length) reject();
                resolve(currentWindowActiveTabs[0].index);
            });
        });
    }
    
    0 讨论(0)
提交回复
热议问题