简体   繁体   中英

get url of current (active) tab for chrome-extension

I found several approaches, but they seem outdated or simply won't work for some reasons for me. Maybe tunnelvision:

First things first:

I have the correct permissions in my manifest.json , I think:

"permissions": [
     "tabs",
    "activeTab"
]

I have 2 simple scripts, background.js and content.js (which are recognized correctly, the error can't be here).

In my background.js I tried several approaches:

chrome.browserAction.onClicked.addListener(buttonClicked);

var sharedUrl;

function buttonClicked(tab) {

chrome.tabs.getCurrent(function(tab) {
   // please read further, this was my last resort, I tried other stuff as well
   sharedUrl = console.log(window.location.href);
});

let msg = {
    txt: "Hello",
    url: sharedUrl
}
chrome.tabs.sendMessage(tab.id, msg);
}

I tried it with getCurrent() and then tab.url , but that didn't work (neither with tab[0].url

I tried it also with getSelected() as well as with something like this:

chrome.tabs.query({active: true, currentWindow: true}, function(arrayOfTabs) {
    var activeTab = arrayOfTabs[0];
});

and my content.js is simply this here:

chrome.runtime.onMessage.addListener(gotMessage);

function gotMessage(message, sender, sendResponse) {
    console.log(message.txt);
    console.log(message.url);
}

It displays "Hello", but not the URL I'm looking for.

Edit: It might of importance, that I want to retrieve the url after a button-click in my extension.

Thanks for the feedback and help.

Ok, based on the documentation you are not able to grab the tab object while you are not in the tab context. The tab context includes only content scripts. So you can't access to tab because you are calling it from your backend page. You can only do it, if your extension has generated the tab.

Gets the tab that this script call is being made from. May be undefined if called from a non-tab context (for example: a background page or popup view).

So, the only possible way is to change your extension data flow.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM