Search code examples
browser-extensioncrossrider

How do we read all the cookies in the background in CrossRider?


We are using CrossRider to develop an extension for Internet Explorer. We are using appAPI.request.get in the background. However, I noticed that the server received the request without cookies.

Are cookies sent to the server when using appAPI.request.get? (if there are cookies to the required domain). And if not, how do we read all the cookies for a specific domain?

We need to read the cookies and that's why I used appAPI.request.get (we have a Python program which returns the cookies in JSON).


Solution

  • OK, I understand that appAPI.request.get doesn't send cookies in the background in Internet Explorer. The solution I found is this: the background will send a message to the active tab, the active tab will use appAPI.request.get to send a message to the server (with the cookies of the specific domain), and will return the cookies to the background. Here is the code:

    Background:

    // get_cookies_url is the url of the script on the server.
    
    var mCallbackMap;
    var message = {message_id: Math.floor((Math.random() * 900000000000000) + 100000000000000)};
    if (typeof mCallbackMap === 'undefined') {
        mCallbackMap = {};
        appAPI.message.addListener({channel: "read_all_cookies_response"}, function(message) {
            if (typeof mCallbackMap[message.message_id] === 'function') {
                mCallbackMap[message.message_id](message.cookies);
                delete mCallbackMap[message.message_id];
            }
        });
    }
    
    (function(callback_inner) {
        mCallbackMap[message.message_id] = function(cookies) {
            if (typeof(callback_inner) === 'function') {
                callback_inner(cookies);
            }
        };
    })(callback);
    
    appAPI.message.toActiveTab({'url': get_cookies_url, 'message_id': message.message_id}, {channel: "read_all_cookies"});
    

    extension.js:

    appAPI.message.addListener({channel: "read_all_cookies"}, function(message) {
        appAPI.request.get({
            url: message.url,
            onSuccess: function(response, additionalInfo) {
                var cookies = JSON.parse(response);
                appAPI.message.toBackground({cookies: cookies, message_id: message.message_id}, {channel: "read_all_cookies_response"});
            }
        });
    });
    

    (mCallbackMap is defined only once and can be related to the controller object, such as Controller.mCallbackMap).