How to fetch URL of current Tab in my chrome exten

2019-01-09 02:56发布

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.

7条回答
【Aperson】
2楼-- · 2019-01-09 03:39

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);
});
查看更多
趁早两清
3楼-- · 2019-01-09 03:39

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.

查看更多
\"骚年 ilove
4楼-- · 2019-01-09 03:42

The simplest method:

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

查看更多
淡お忘
5楼-- · 2019-01-09 03:43

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!

查看更多
ら.Afraid
6楼-- · 2019-01-09 03:46

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.

查看更多
相关推荐>>
7楼-- · 2019-01-09 03:48

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

查看更多
登录 后发表回答