admin管理员组

文章数量:1287775

The following code doesn't work for some reason:

Background.js

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

manifest.json

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

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

The following code doesn't work for some reason:

Background.js

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

manifest.json

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

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

Share Improve this question edited Jan 10, 2018 at 15:59 Stan Lindsey asked Jan 21, 2013 at 22:01 Stan LindseyStan Lindsey 4851 gold badge5 silver badges12 bronze badges 3
  • What does the javascript console say? – John Dvorak Commented Jan 21, 2013 at 22:05
  • 1 I can't see any chrome.cookies in my console. Is that a specialty just for extensions? – John Dvorak Commented Jan 21, 2013 at 22:10
  • Yeah mine is blank too, thats why I'm using alerts. – Stan Lindsey Commented Jan 21, 2013 at 22:30
Add a ment  | 

2 Answers 2

Reset to default 8

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./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./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./extensions/cookies.html and open developer tools as shown here, you can see cookie is being set!.

Click for Large Image

Further Debugging

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

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."
  ],
  ...
}

source: developer.chrome.

本文标签: javascriptchromecookiesset doesn39t even runStack Overflow