0

I am attempting to retrieve the current url in a chrome extension from the content script. From searching, it sounds like the best way to retrieve the current url is to use chrome.tabs.query, however this must be done from a background page, so that's what I've attempted to implement.

Side note, document.location.href does seem to work in the content script, but I haven't seen this suggested as a workaround. Are there concerns with using this instead?

As for making it work with chrome.tabs.query, here is my function in the content script:

function getWebApiServer() {
    console.log(document.location.href);
    chrome.runtime.sendMessage({request: 'url'}, function(response) {
        console.log(response);
    });
}

That function has these logs in the browser:

https://host/extension contentscript.js:165
undefined contentscript.js:167

And here is my background script:

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        console.log(request)
        chrome.tabs.query({
            active: true,
            lastFocusedWindow: true
        }, function(tabs) {
            var tab = tabs[0];
            console.log(tab['url']);
            sendResponse('Message received');
            console.log(sendResponse);
            // sendResponse(tab['url']);

        });

        // sendResponse('Message received');
});

Which has these logs in the background page:

Object {request: "url"} event.js:3

https://host/extension event.js:9

function (response) { event.js:11

I can see that nothing is returned to the content script as is, but if I uncomment the last line of the background script, I will get a 'Message received' response in content scripts.

This leads me to the main question, why am I not able to call sendResponse in the chrome.tabs.query callback?

hwustrack
  • 67
  • 3
  • 8
  • Chrome API is async, `chrome.tabs.query` included, that's why you need to prevent message channel from closing as shown in the linked duplicate. – wOxxOm Aug 10 '16 at 00:49
  • short answer, return true where you have the commented out sendResponse - long answer, see the link @wOxxOm posted – Jaromanda X Aug 10 '16 at 00:50

0 Answers0