chrome-extensions-samples/functional-samples/libraries-xhr-in-sw
patrick kettner d2fd736ac0
Add an example that shows how to polyfill XHR in an extension (#1343)
* 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
2024-11-07 04:30:06 -05:00
..
sidepanel Add an example that shows how to polyfill XHR in an extension (#1343) 2024-11-07 04:30:06 -05:00
third_party Add an example that shows how to polyfill XHR in an extension (#1343) 2024-11-07 04:30:06 -05:00
.gitignore Add an example that shows how to polyfill XHR in an extension (#1343) 2024-11-07 04:30:06 -05:00
README.md Add an example that shows how to polyfill XHR in an extension (#1343) 2024-11-07 04:30:06 -05:00
background.js Add an example that shows how to polyfill XHR in an extension (#1343) 2024-11-07 04:30:06 -05:00
manifest.json Add an example that shows how to polyfill XHR in an extension (#1343) 2024-11-07 04:30:06 -05:00
package-lock.json Add an example that shows how to polyfill XHR in an extension (#1343) 2024-11-07 04:30:06 -05:00
package.json Add an example that shows how to polyfill XHR in an extension (#1343) 2024-11-07 04:30:06 -05:00
rollup.config.mjs Add an example that shows how to polyfill XHR in an extension (#1343) 2024-11-07 04:30:06 -05:00

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

  1. Clone this repository
  2. Run npm install in this folder to install all dependencies.
  3. Run npm run build to bundle the extension.