javascriptgoogle-chromegoogle-chrome-extensionpopupwindow

Obtain URL's of chrome popups


I have written a piece of code which alerts the tab URL after every 2 seconds. However, I am unable to do this for pop-ups. Whenever I open a pop-up; the tab url is of the background page and not the pop-up.

How can i get the url of the pop-up in crome?

<script>
var seconds = 2*1000;
setInterval(function(){
    chrome.tabs.getSelected(null, function(tab) {
        tabId = tab.id;
        tabUrl = tab.url;
        alert(tabUrl);
});
},seconds);
</script>
</head>

Solution

  • In content_script.js or popup.html:

    function get_urlInfo() {
       var d = {
          'action' : 'getUrl'
       };
    
       chrome.extension.sendRequest(d, function(response) {
           alert(response.url);
       });
    };
    

    In background.html:

    function onRequest(request, sender, sendResponse) { 
       if (request.action == 'getUrl') {
          sendResponse({'url' : sender.tab.url});                       
       }
    };
    
    chrome.extension.onRequest.addListener(onRequest);  
    

    It should work!