2013-05-26 117 views
0

如何將當前選項卡的URL存儲在變量中以便稍後可以訪問?我做了一些Google搜索,但不太瞭解異步回調函數。全局變量和異步回調函數

var currentTab;
chrome.tabs.getSelected(null, function(tab) { currentTab = tab.url; });
console.log(currentTab);

+0

[在調用chrome.tabs.query後,結果不可用](http://stackoverflow.com/a/11689804/938089)在Chrome擴展的上下文中解釋異步代碼的概念,讀取它並試着去理解這個比喻。 –

+0

啊好吧我_kind of_明白現在發生了什麼。所以我無法訪問設置_side_異步函數的變量,即使它在頂部(全局)聲明? – user2409821

+0

當然不是你在問題中寫的方式。你必須以某種方式延遲對變量的訪問,所以在另一個答案中提出的解決方案是最好的選擇(另一種方法是使用定時器,例如'setTimeout',但這會導致不可預知的結果)。 –

回答

0

的所有Chrome方法是異步的,這意味着他們只是排隊代碼稍後調用。

另請注意,tabs.getSelectedhas been deprecated,所以我用tabs.query({active: true}...來代替。

回調火災壞了,一切結束後:

var currentTab;     // 1 

chrome.tabs.query({active: true}, // 2, queues up callback and continues 
    function(tabs) { 
     currentTab = tabs[0].url; // 4, last, after everything else 
    }); 

console.log(currentTab);   // 3 callback hasn't fired yet, so undefined 

歡迎什麼有時也被稱爲「回調地獄」。

最簡單的解決方法是使用異步或promise包裝庫,如chrome-extension-async。這使你可以使用async/await語法:

async function yourCode() { 
    try { 
     const currentTabs = await chrome.tabs.query({active: true}); 
     const currentTab = currentTabs[0]; 
     console.log(currentTab); 
    } 
    catch(err) { 
     // Log errors etc 
    } 
} 

你還在做一個回調,它的結束後執行的代碼,但現在你可以前後await後容易使用變量。我最近blogged about that in a lot more detail than will fit here