Stan Lindsey
Stan Lindsey

Reputation: 485

chrome.cookies.set doesn't even run

The following code doesn't work for some reason:

Background.js

alert("1");
chrome.cookies.set({ url: "https://mywebsite.com", name: "SuperDuperTest" });
alert("2");

manifest.json

"permissions": [ "notifications", "https://mywebsite.com", "cookies", "http://* /* ", "https://* / * " ],

Only alert("1"); ever fires. Alert 2 never does, why isn't my chrome cookies firing at all?

Upvotes: 2

Views: 14179

Answers (2)

Sudarshan
Sudarshan

Reputation: 18534

Where are looking to check whether your cookie is set or not? Please use console.log() instead of alert()

Sample Code

manifest.json

Registered background page and given permissions for Cookies API.

{
    "name": "Cookie API Demo",
    "version": "1",
    "description": "http://stackoverflow.com/questions/14448039/chrome-cookies-set-doesnt-even-run",
    "permissions": [
        "cookies",
        "<all_urls>"
    ],
    "background": {
        "scripts": [
            "background.js"
        ]
    },
    "manifest_version": 2
}

background.js

Trivial code to set cookie for cookies.html page

chrome.cookies.set({
    "name": "Sample1",
    "url": "http://developer.chrome.com/extensions/cookies.html",
    "value": "Dummy Data"
}, function (cookie) {
    console.log(JSON.stringify(cookie));
    console.log(chrome.extension.lastError);
    console.log(chrome.runtime.lastError);
});

Output

Go to https://developer.chrome.com/extensions/cookies.html and open developer tools as shown here, you can see cookie is being set!.

Click for Large Image

enter image description here

Further Debugging

If this sample code does not work, what are values of chrome.extension.lastError and chrome.runtime.lastError?

Upvotes: 8

P1nGu1n
P1nGu1n

Reputation: 594

Make sure you declared the cookies permission.

To use the cookies API, you must declare the "cookies" permission in your manifest, along with host permissions for any hosts whose cookies you want to access. For example:

{
  "name": "My extension",
  ...
  "permissions": [
    "cookies",
    "*://*.google.com"
  ],
  ...
}

source: developer.chrome.com

Upvotes: 1

Related Questions