首页 文章

获取当前标签并将其传递到Chrome扩展程序中的变量

提问于
浏览
0

我正在尝试创建一个返回当前标签页面的函数:

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

我用的时候:

chrome.tabs.getSelected(null, function(tab) {alert(tab.url);});

Chrome会显示网址,但如果我在Chrome控制台中使用我的功能,则该功能会返回“” .

有没有办法将tab.url传递给变量然后返回此变量?

1 回答

  • 6

    chrome.tabs.getSelectedasynchronous . 这意味着当调用回调函数时, return url "has already occurred" .

    你有两个选择来达到预期的效果 .

    代码为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] || '';
    }
    

相关问题