3

I'm writing a chrome extension. I want to store some data in the browser cookie so that I can use it later. Cookie is a perfect way to do that. Does chrome extension have it's own document cookie for this like all the websites?

I got this result when I did some research https://developer.chrome.com/extensions/cookies But it mostly talks about cookie API and getting cookies of other websites hence the question. Also does chrome storage have any advantages over using a cookie? I just need to store 2/3 key value pairs. https://developer.chrome.com/apps/storage

Xan
  • 74,770
  • 16
  • 179
  • 206
sublime
  • 4,013
  • 9
  • 53
  • 92

2 Answers2

8

I will say Just one line and you will understand it.

Cookies are always related to a website/domain.

It does not make sense to ask if Chrome extension has a cookie. You can have a cookie for every domain.

Some more information to help you solve your problem. If you see chrome extension model, you can see there are

  1. Background Scripts
  2. Content Scripts
  3. Popup Page/Scripts

If you want to store cookie in a background script/ popup script, then you can definitely do it. But that cookie will be saved for the domain of your background script which is essentially your chrome extension id.

If you store cookie in a content script, then you are storing information in cookie which belongs to the domain on which your content script is injected.

Sachin Jain
  • 21,353
  • 33
  • 103
  • 168
4

One one hand, yes, cookies are available in Chrome extensions. But this is a very unorthodox method of storing data in extensions.

As you correctly pointed out, chrome.cookies API is for manipulating other pages' cookies. The common way of working with cookies in JS is document.cookie.

What are the common ways to store persistent data?

Two classic ways are localStorage and chrome.storage.

I've answered about them before; see this answer for comparison between them, and this answer for a usage example.

To decide what you need, the most important question is: do you need to access data from a content script?

  • If no, using localStorage may be simpler.
  • If yes, you will need to use either chrome.storage, or message passing.
Community
  • 1
  • 1
Xan
  • 74,770
  • 16
  • 179
  • 206