Get current tab and pass it to variable in a Chrome Extension

前端 未结 1 1537
予麋鹿
予麋鹿 2020-12-20 09:58

I\'m trying to create a function that returns the current tab url:

function tabURL() {
var url=\"\";
chrome.tabs.getSelected(null, function(tab) {url = tab.u         


        
相关标签:
1条回答
  • 2020-12-20 10:33

    chrome.tabs.getSelected is asynchronous. That means that when the callback function is called, return url "has already occurred".

    You've got two options to achieve the desired effect.

    1. Properly rewrite your code, to correctly implement the asynchronous aspect (the exact details depends on your extension's implementation).
      Note that getSelected has been deprecated and replaced with chrome.tabs.query since Chrome 16.

    2. Maintain a hash with the current URLs using chrome.tabs.onUpdated (add tabID + URL), chrome.tabs.onRemoved (to remove obsolete entries) and chrome.tabs.onActivated (to set the current active tab).

    Code for 2:

    // Our hash
    var tabIdToURL = {};
    var currentTabId = -1;
    // Add changes to the hash (tab creation, tab's page load)
    chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
        tabIdToURL[tabId] = tab.url; // also available as tab.id and changeInfo.url
    });
    // Remove entries from closed tabs
    chrome.tabs.onRemoved.addListener(function(tabId) {
        delete tabIdToURL[tabId];
    });
    // Set the ID of the current active tab
    chrome.tabs.onActivated.addListener(function(activeInfo) {
        currentTabId = activeInfo.tabId;
    });
    
    // Usage, based on the question's function
    function getURL() {
        return tabIdToURL[currentTabId] || '';
    }
    
    0 讨论(0)
提交回复
热议问题