4

My extension adds notify to third-party websites. From this notify I should check if user is logged on our website. I want to check userId from cookies in background.js and send message to content.js. Where I need to know if cookies not empty ( chrome.cookies.get doesn't available from content.js).

Simple response from https://developer.chrome.com/extensions/messaging works perfectly. And chrome.cookies.get works fine separetaly. But when I try to add condition with get.cookies there is a problem. I guess it because scoupe/context or callbacks trouble.

Background.js

Chrome.runtime.onMessage.addListener(
    function (request, sender, sendResponse) {
        if (request.greeting == "hello") {
            var ID;

            function getCookies(domain, name) {
                chrome.cookies.get({"url": domain, "name": name}, function (cookie) {
                    ID = cookie.value;
                    showId();
                });
            }

            function showId() {
                if (ID) {
                    sendResponse({farewell: "logged"});
                }
                ;
            }

            getCookies(baseUrl, COOKIE_KEY_USER_ID);
        }
    }
);

content.js

$(notify).find('[data-act]').on('click', function (e) {
    e.preventDefault();

    chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
        if (response && response.farewell == "logged") {
            activateFromNotify();
        } else {
            // 'not logged'
            $('.wrapper').html(showlogin);
        };
    });

});

Looks like in background.js it doesnt see sendResponse inside another function or Callback. Is there any way to resolve it ?

Upd: changed construction in background.js and it works fine:

 browserObj.runtime.onMessage.addListener(
            function(request, sender, sendResponse) {
                if (request.greeting == "hello"){
                    checkUserLogin(request, sender, sendResponse);
                };
                return true;
            });

        function checkUserLogin(request, sender, sendResponse){
            var resp = sendResponse;
            browserObj.cookies.get({'url': baseUrl, 'name': COOKIE_KEY_USER_ID}, function (cookie) {
                        var userId = cookie && cookie.value ? cookie.value : 0;


                resp({farewell: userId});


            });

        }
allweek
  • 41
  • 4
  • Possible duplicate of [Chrome Extension Message passing: response not sent](https://stackoverflow.com/questions/20077487/chrome-extension-message-passing-response-not-sent) – wOxxOm Apr 27 '18 at 13:26
  • Well, tnank you so much! Finally I've changed my construction to similar in the answer and add return true. Now it works – allweek Apr 27 '18 at 16:04

0 Answers0