⚠ Deprecated: this project is no longer needed when using Chrome Manifest v3. It is recommended to switch from Manifest v3 as v2 is currently phasing out.
Axios adapter to pass the requests to a Chrome Extension background script. Useful to avoid CORB in content scripts.
More informations about CORB here and here.
This axios adapter is only intended to be used in Chrome extensions, it simply forwards axios requests to the background script, using the chrome.runtime.sendMessage(...)
API.
$ npm install --save axios-chrome-messaging-adapter
$ # Or
$ yarn add axios-chrome-messaging-adapter
Axios must be available as a global object so you'll need to import it from a CDN too, we use unpkg here as an example.
<script src="https://unpkg.com/[email protected]/dist/axios.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/axios-chrome-messaging-adapter.min.js"></script>
If you are using a bundler, like webpack or rollup:, you'll just need to require
the lib. If you are using a CDN, the lib will be available under window.axiosChromeMessagingAdapter
.
In your background script:
import axios from 'axios';
import { registerMessageHandler } from 'axios-chrome-messaging-adapter';
// register the adapter message hanlder
registerMessageHandler();
In your content script:
import axios from 'axios'
import { adapter } from 'axios-chrome-messaging-adapter'
// tell axios to use the adapter for this request
const axiosInstance = axios.create({
adapter,
... // the rest of your configuration :)
})
The adapter is currently incompatible with the following axios parameters:
- paramsSerializer
- onUploadProgress
- onDownloadProgress
- cancelToken
- transformRequest (axios 0.19+)
- transformResponse (axios 0.19+)
This limitation is due to the fact that only scalar values can pass through the chrome messaging API, making these callbacks functions unavailable for the moment.
If one of these options is used, it will be ignored and the content script will emit a warning.
When using this adapter with a chrome extension using Manifest V3, XMLHttpRequest
isn't available in the service worker (former background script) so the default axios adapter won't work…
To solve this issue, you have to specify a custom adapter that works in this context. I recommend using @vespaiach/axios-fetch-adapter.
import axios from 'axios';
import { registerMessageHandler } from 'axios-chrome-messaging-adapter';
import fetchAdapter from '@vespaiach/axios-fetch-adapter';
// register the adapter message handler and use the custom adapter
registerMessageHandler({ adapter: fetchAdapter });
Clone the project to the directory and install dependencies
$ git clone https://github.com/dzetah/axios-chrome-messaging-adapter
$ cd axios-chrome-messaging-adapter
$ yarn # or npm install
$ npm i --no-save axios # install axios peer dependency
Start typescript compilation in watch mode
$ npm run watch