Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.6k views
in Technique[技术] by (71.8m points)

google chrome extension - how to get current tabId from background page

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

background.html

<html>
<head>
    <script>

    if(typeof localStorage.state == 'undefined')
        localStorage.state = 'off'
    chrome.browserAction.onClicked.addListener(function(tab) {
        if(localStorage.state == 'on')
        {
            localStorage.state = 'off';
        }
        else
        {
            localStorage.state = 'on';
        }
        chrome.browserAction.setBadgeText({text: localStorage.state, tabId: tab.id});
        chrome.tabs.sendRequest(tab.id, {state: localStorage.state});
        //chrome.tabs.sendRequest(tab.id, {state: localStorage.state});
    });
    </script>
</head>

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 } );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...