8
  "manifest_version": 3,
  "background": {
    "service_worker": "background.js"
  }

I need to use Jquery in background.js. I cannot add jquery.min.js in the manifest because with the new upgrade v3 I cannot declare more than one JS in service_worker. How can I solve?

background.js

$.ajax({
   type: "POST",
   url: "https://wwww",
   data: {text: "xxx"}
});
sparkle
  • 6,940
  • 19
  • 64
  • 107

1 Answers1

6

jQuery is DOM-based so its $.ajax or $.put or $.get won't run in the service worker as there's no DOM/document/window, consequently no XMLHttpRequest, which is used by these methods. The other DOM-based features of jQuery are also unusable in a service worker.

The solution is to use fetch().
There are also fetch-based libraries if you need more bells and whistles like onprogress.

If you still want to use its other utility functions, call importScripts('jquery.min.js') MDN inside background.js, which will synchronously import the listed scripts so they can be used immediately afterwards (more info here),

wOxxOm
  • 53,493
  • 8
  • 111
  • 119
  • 2
    I have added "importScripts('js/jquery.js')" but it get error "Service worker registration failed" – sparkle Mar 04 '21 at 11:36
  • It means the path is incorrect, see the more info link in the answer for workarounds. – wOxxOm Mar 04 '21 at 11:38
  • Another possibility is that jquery.js failed because workers don't have DOM. Like I said, don't use jquery.\ – wOxxOm Mar 04 '21 at 11:39