d2fd736ac0
* add an example that shows how to polyfill XHR in an extension * updates from feedback * update based on third party OSS requirements * update readme links |
||
---|---|---|
.. | ||
sidepanel | ||
third_party | ||
.gitignore | ||
README.md | ||
background.js | ||
manifest.json | ||
package-lock.json | ||
package.json | ||
rollup.config.mjs |
README.md
Using XHR in Service Workers
This sample demonstrates how to use code that relies on XHR within a extension's background service worker.
Overview
The default background environment for extensions is the service worker. As a result, it only has direct access to Fetch. If you want to use a library that is built with XHR, this will not work by default. However, you can usually monkeypatch the expected behavior by polyfilling XHR. This sample shows an example of how you can use build tools to automatically inject a polyfill for XHR that covers most common XHR use cases, allowing for seamless integration into your extension.
In this sample, we are using a "library" that exports a function called fetchTitle
. For the fiction of this sample, this is a dependency we must use, but we are unable to change ourselves. Unfortunately, it uses XHR. In order to make this work, we import a shim, and then set the global XMLHttpRequest
to it.
This is all packaged by a build system, in this case Rollup.
Running this extension
- Clone this repository
- Run
npm install
in this folder to install all dependencies. - Run
npm run build
to bundle the extension.