2016-06-14 20 views
0

這工作得很好如何使用標籤的網址外chrome.tabs.query

var tabUrl; 

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { 
    tabUrl = tabs[0].url; 
    console.log(tabUrl); 
}); 

,但這個節目未定義

var tabUrl; 

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { 
    tabUrl = tabs[0].url; 
}); 

console.log(tabUrl); 

但是我要檢查URL根據改變我popup.html用戶正在瀏覽的頁面,但我不想在chrome.tabs.query函數中執行此操作。

+0

審查異步概念[這裏](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous -all) –

+0

非常感謝你@IvánNokonoko – spyagentsss

回答

0

根據W3關於Javascript變量作用域的說明。爲了訪問函數中的變量,您不能在之前添加var標記,並使用window.Variable來訪問它。

這應該工作:

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { 

tabUrl = tabs[0].url; 
}); 


console.log(window.tabUrl); 
+0

'chrome.tabs.query'異步工作。變量'window.tabUrl'仍然是未定義的,因爲它在執行回調函數之前被訪問。 –