How to fetch URL of current Tab in my chrome exten

2019-01-09 03:11发布

问题:

I am just getting started with Google Chrome Extension development and my project involves making an extension which when clicked prints the URL of whichever page/tab is currently open.

So if I am on google's home page and I click my extension, I need to get "https://www.google.com/" as my output within the extension.

I need to do this using javascript and am unable to find code which I understand and which does the job. I read about using "window.location" and "document.href" and stuff but won't that give me the url of just my extension and not the current tab?

Please help me get started. Thanks in advance.

回答1:

Try

chrome.tabs.getCurrent(function(tab){
        console.log(tab.url);
    }
);

Note you must have the tabs permission set in your manifest file

"permissions": [
    "tabs"
],

http://developer.chrome.com/extensions/tabs.html

or the activeTab permission if initiated by a click on the extension button[Xan]

https://developer.chrome.com/extensions/activeTab


If the above doesn't work try

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


回答2:

Using javascript, it will work if you are not using it in popup because javascript in popup will return url of popup therefore, in popup, you have to use Chrome tab API and set permission in Chrome manifest.

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

So best way is to use Chrome tab API



回答3:

You need to be careful with what you mean by "current tab". If the user has more than one window open, each of them with multiple tabs, Chrome defines the "current window" as the one that is running the content script that makes use of the chrome.tabs API. That happened to me and I solved it by referencing not the "current" window but the last focused one:

chrome.tabs.query({ active: true, lastFocusedWindow: true }, function (tabs) {
    // Do something
});

References:

https://developer.chrome.com/extensions/windows#current-window https://developer.chrome.com/extensions/tabs#method-query

Hope it helps!



回答4:

UPDATE: this method is now deprecated, so please don't use it

In my case any above has not worked. So I used this:

chrome.tabs.getSelected(null, function(tab) {
    console.log(tab.url)
})

and it worked great! Hope it helps.



回答5:

this worked for me give it a try

chrome.tabs.query({
active: true,
lastFocusedWindow: true
}, function(tabs) {
// and use that tab to fill in out title and url
var tab = tabs[0];
console.log(tab.url);
alert(tab.url);
 });


回答6:

DO NOT use getSelected

As per the Chrome Developer Docs: chrome.tabs.getSelected has been deprecated since Chrome ver.33

Instead use:

chrome.tabs.query({active:true}, __someCallbackFunction__) like Musa's second suggestion.



回答7:

The simplest method:

console.log('current url' + window.location)