Question

I've got a simple function that just passes location.href from contentscript to the popup.html page. It's not working. what I've got is..

in popup.html..

        chrome.tabs.getSelected(null,function(tab)
            {
            chrome.tabs.sendRequest({req: "getlocation"}, function(response){
            return response.reply;
            });
            });

in my contentscript...

        case "getlocation":
        sendResponse({
            reply: location.href
            });
     break;

Why isn't my code working?

Was it helpful?

Solution

Some params are missing, plus you can't use return from an async callback function.

popup.html:

function getCurrentUrl(callback){
    chrome.tabs.getSelected(null,function(tab){
        chrome.tabs.sendRequest(tab.id, {req: "getlocation"}, function(response){
            callback(response.reply);
        });
    });
}

getCurrentUrl(function(url){
    console.log("url:", url);
});

content_script.js:

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
    switch(request.req) {
        case "getlocation": 
            sendResponse({
                reply: window.location.href
            });
            break;
    }
});

OTHER TIPS

sendRequest is outdated.

use sendMessage

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top