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

use*_*284 0 google-chrome google-chrome-extension

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

function tabURL() {
var url="";
chrome.tabs.getSelected(null, function(tab) {url = tab.url;});
return url;
}
Run Code Online (Sandbox Code Playgroud)

我用的时候:

chrome.tabs.getSelected(null, function(tab) {alert(tab.url);});
Run Code Online (Sandbox Code Playgroud)

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

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

Rob*_*b W 6

chrome.tabs.getSelected异步的.这意味着当调用回调函数时,return url"已经发生".

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

  1. 正确地重写代码,正确实现异步方面(具体细节取决于扩展的实现).
    请注意,自Chrome 16以来getSelected弃用并替换chrome.tabs.query.

  2. 使用chrome.tabs.onUpdated(添加tabID + URL),chrome.tabs.onRemoved(删除过时的条目)和chrome.tabs.onActivated(设置当前活动选项卡)维护当前URL的哈希.

代码为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] || '';
}
Run Code Online (Sandbox Code Playgroud)