Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
507 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>

question from:https://stackoverflow.com/questions/7303452/how-to-get-current-tabid-from-background-page

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

1 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...