flying sheep
flying sheep

Reputation: 8942

Use the browser cookie in fetch in a WebExtension

I’m currently porting an addon from the jetpack to the WebExtension API. I need to continuously update a browser action (toolbar button) with data (e.g. set its badge text).

For this, I would like to do a request from a background script in my extension to an API of the page, which is accessible when the user is logged in (i.e. a cookie is set). What I did so far:

  1. I gave myself host permissions, which is mentioned to be necessary for request from content scripts.

    However, content scripts are for injecting JS into pages the user visits.

  2. I created a background script that uses fetch to do a request to the API.

However, when queried from the background script, the API tells me that nobody is logged in, while I can access it with the browser flawlessly.

This is the relevant part of the manifest.json:

{
  "background": {
    "scripts": ["background.js"]
  },
  "permissions": [
    "*://subdomain.domain.com/*"
  ]
}

How can I have a continuously running background script that can use the user’s cookie to access this API?

Upvotes: 2

Views: 1127

Answers (2)

Hammad Akhwand
Hammad Akhwand

Reputation: 799

Firefox has stricter cors restrictions for cookies. I solved this by doing the api call from a content-script injected on the page with the same domain. That api call generated an auth token that was used for api calls from the background page, and enabling cors on backend for requests containing token in auth header.

Upvotes: 1

Andrew Swan
Andrew Swan

Reputation: 1343

You'll need to supply the credentials option in the arguments to fetch()

https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch

Upvotes: 0

Related Questions