1

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?

2 Answers 2

2

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;
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

Whats the callback param you have?
@Skizit I assumed your code in popup is a part of some utility function because you are using return there. You can't use return with received value inside chrome.tabs.sendRequest, you need to pass received value to some other function, I made it so it will be passed to a callback function. If you don't need to pass received url anywhere then you can just do everything inside chrome.tabs.sendRequest.
0

sendRequest is outdated.

use sendMessage

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.