Getting the tab id or url and displaying it with getCurrent

Here is my script.js and background.html content and error

contentscript.js

chrome.extension.sendRequest({"type":""}); 

background.html

 <script type="text/javascript" charset="utf-8"> chrome.extension.onRequest.addListener( function(request, sender, sendResponse) { chrome.tabs.getCurrent(function(tab){var urls = tab.url;console.log(urls);}); }); </script> 

Error message on background.html console

background.html: 7 Uncaught TypeError: Unable to read property 'url' from undefined

It should be an easy change, but I'm stuck.

+4
source share
3 answers

You cannot invoke get getCurrent because you do not invoke it from the tab context. The documentation says that you also cannot use this. You can only use this if your extension has created a tab. You want to grab your Tab id in order to use it with the extension. There is no tab for the background page.

Gets the tab with which this script call is executed. It can be undefined if called from a context without tabs ( for example: a background page or a popup view ).

If you want to get the current tab id, you can use chrome.tabs.getSelected , which will let you get its URL and id.

+5
source

Hm, that really doesn't work. I would like to hear the reason myself, but meanwhile here is a workaround:

 chrome.extension.onRequest.addListener(function(request, sender, sendResponse) { console.log(sender.tab.url); }); 
+1
source

you can try it

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

Source: https://habr.com/ru/post/1337582/


All Articles