How can I get the URL of the current tab from a Google Chrome extension?
我对Google Chrome扩展程序很有趣,我只想知道如何将当前选项卡的URL存储在变量中?
Update: The chrome.tabs.getSelected()
method is now deprecated.
The recommended way of getting the URL of the current tab is to use chrome.tabs.query()
.
An example usage:
chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
var url = tabs[0].url;
});
This requires that you request access to the chrome.tabs
API in your extension manifest:
"permissions": [ ...
"tabs"
]
It's important to note that the definition of your "current tab" may differ depending on your extension's needs.
Setting lastFocusedWindow: true
in the query is appropriate when you want to access the current tab in the user's focused window (typically the topmost window).
Setting currentWindow: true
allows you to get the current tab in the window where your extension's code is currently executing. For example, this might be useful if your extension creates a new window / popup (changing focus), but still wants to access tab information from the window where the extension was run.
I chose to use lastFocusedWindow: true
in this example, because Google calls out cases in which currentWindow
may not always be present.
You are free to further refine your tab query using any of the properties defined here: chrome.tabs.query
A friend answers to my question.
First, you've to set the permissions for the tab API :
"permissions": [
"tabs"
]
And to store the URL :
chrome.tabs.getSelected(null,function(tab) {
var tablink = tab.url;
});
The problem is that chrome.tabs.getSelected is asynchronous. This code below will generally not work as expected. The value of 'tablink' will still be undefined when it is written to the console because getSelected has not yet invoked the callback that resets the value:
var tablink;
chrome.tabs.getSelected(null,function(tab) {
tablink = tab.url;
});
console.log(tablink);
The solution is to wrap the code where you will be using the value in a function and have that invoked by getSelected. In this way you are guaranteed to always have a value set, because your code will have to wait for the value to be provided before it is executed.
Try something like:
chrome.tabs.getSelected(null, function(tab) {
myFunction(tab.url);
});
function myFunction(tablink) {
// do stuff here
console.log(tablink);
}
链接地址: http://www.djcxy.com/p/91126.html