0

My chrome extensions Content script uses a chrome.runtime.sendMessage to send a message to my Background script, which then needs to read the cookies and return these in the 'sendResponse'.. code below:

ContentScript.js

chrome.runtime.sendMessage({getcookies: "Get me cookies"}, function (response){
    console.log(response.cookieList);
});

BackgroundScript.js

var cookiesFinal;
chrome.runtime.onMessage.addListener(function(res, sender, sendResponse) {
    chrome.cookies.get({ url: 'https://www.example.com/', name: 'cookie1' }, function GetCookies(cookies) {
        cookiesFinal = cookies;
    });
    sendResponse(cookiesList: cookiesFinal);
});

However when I run this I get an error saying 'cannot read value of cookieList: undefined?

Any tips on how I can make this work?

jianweichuah
  • 1,417
  • 1
  • 11
  • 22
  • 1
    See also `onMessage` documentation: you need to `return true` for an async response. – Xan Dec 19 '15 at 22:24

1 Answers1

0

I can see 2 problems:

  1. sendResponse(cookiesList: cookiesFinal) is not in JSON format. It should be sendResponse({cookiesList: cookiesFinal})

  2. The callback for chrome.cookies.get is asynchronous. So, cookiesFinal might still be undefined when you're sending the response before you're getting the cookies back.

The way around it can be sending another message to the content script when you've retrieved the cookies in the callback function.

jianweichuah
  • 1,417
  • 1
  • 11
  • 22