Garmaine Staff asked 1 year ago

I started writing a chrome-extension to backup store and load cookies. The code basicly runs fine, but when I'm loading the stored cookies, I'm not logged in anymore. Is this a problem on my side or is it not possible to log in by setting cookies?

Here is my code for loading and storing the cookies:

var storeButton = document.getElementById("store");

storeButton.onclick = function() {
    chrome.cookies.getAll({}, function(cookies) {
        document.getElementById("jar").innerHTML = "";
        for(var i = 0; i < cookies.length; i++) {
            document.getElementById("jar").innerHTML += cookies[i].name + "<br>";
        }

        chrome.storage.local.set({cookies: cookies}, function() {
            document.getElementById("test").innerHTML = cookies.length + " cookies stored";
        });
    });
}

function loadCookies(cookies) {
    for(var i = 0; i < cookies.length; i++) {
        document.getElementById("test").innerHTML = cookies[i].name;

        chrome.cookies.set(
            {
            url: "https://" + (cookies[i].domain.startsWith(".") ? "www" : "") + cookies[i].domain  + cookies[i].path, 
            name: cookies[i].name, 
            value: cookies[i].value, 
            secure: cookies[i].secure,
            httpOnly: cookies[i].httpOnly,
            sameSite: cookies[i].sameSite,
            expirationDate: cookies[i].expirationDate,
            storeId: cookies[i].storeId
            }, 
            function(cookie) {
            }
        );
    }
}

var loadButton = document.getElementById("load");

loadButton.onclick = function() {
    chrome.storage.local.get(['cookies'], function(result) {
        cookies = result.cookies;

        if (cookies == undefined) {
            document.getElementById("test").innerHTML = "No cookies stored";
            return;
        }

        chrome.cookies.getAll({}, function(oldCookies) {
            if (oldCookies.length == 0) {
                loadCookies(cookies);
            }

            var removedCookies = 0;
            for(var i = 0; i < oldCookies.length; i++) {
                chrome.cookies.remove({url: "https://" + oldCookies[i].domain + oldCookies[i].path, name: oldCookies[i].name}, function() {
                    removedCookies++;
                    if (removedCookies >= oldCookies.length) {
                        loadCookies(cookies);
                    }
                });
            }
        });
    });
}