chrome.tabs.query
支持从后台页面,当然只要你有tabs
权限。这是支持的路线为Chrome浏览器19
chrome.tabs.query({
active: true,
currentWindow: true
}, function(tabs) {
var tab = tabs[0];
var url = tab.url;
});
注意,因为它会否则返回活动选项卡每窗口currentWindow
需要的。这应该保证只返回一个选项卡。
当然,请记住,这是一个异步API--除了在回调函数中,您不能访问它提供的任何数据。您可以将值(例如url
)存储在更高的范围内,以便其他函数可以访问它,但在执行回调后仍然会提供正确的结果。
(下面是我原来的答复一直为后人 - 这个方法是不再需要,需要经常运行的后台页面,getSelected()
已过时)
首先把这个背景.html和使myURL可变全球:
var myURL = "about:blank"; // A default url just in case below code doesn't work
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) { // onUpdated should fire when the selected tab is changed or a link is clicked
chrome.tabs.getSelected(null, function(tab) {
myURL = tab.url;
});
});
然后在popup.html运行时您希望得到的页面网址:
chrome.extension.getBackgroundPage().myURL;
因此,如果我要让它出现在弹出窗口中,并且我去Google并点击了您的页面或浏览器操作,我会在弹出窗口中看到http://google.com/webhp
。
谢谢!完美的作品。 – Calvin