javascriptcookiessafari-extensionweb-extension

Setting cookies not allowed in extension popup?


I'm trying to set a cookie in the popup page of my extension to no avail. I've tried two different methods...

First I used document.cookie, which doesn't do anything...

document.cookie = "SID=1234";
console.log("Current cookie...");
console.log(document.cookie);

Console Output:

Current cookie...
[empty line]

Then I tried using cookieStore.set(), which throws an error...

async function setCookie() {
    try {
        await cookieStore.set({
            name: "SID",
            value: "1234"
        });
    } catch (error) {
        console.log(`Error setting SID: ${error}`);
    }
}
await setCookie();

Console Output:

Error setting SID: TypeError: The domain must domain-match current host

I tried adding in the current domain but that didn't work either...

async function setCookie() {
    try {
        await cookieStore.set({
            name: "SID",
            value: "1234",
            domain: window.location.href
        });
    } catch (error) {
        console.log(`Error setting SID: ${error}`);
    }
}
await setCookie();

Console Output:

Error setting SID: TypeError: The domain must domain-match current host

Is there something I'm missing here? Or are you just not allowed to set cookies in the popup page of an extension?


Solution

  • The steps should be:

    Set permission for cookies in your extension manifest.json:

      "permissions": [
        "cookies",
         .......
      ],
    

    Set permission for the host, only then can you change cookies of the host:

     "host_permissions": [
        "*://*.google.com/", ....
      ],
    

    Then call cookies.set

    browser.cookies.set({
      url: currentURL,
      name: "SID",
      value: '1234',
    });
    

    Getting currentURL can be tricky as you might want url of not the popup but the tab. Find it here