4

How to make a JSONP request inside a Service Worker?

As you may know, a Service Worker doesn't have document. Therefore many javascript approaches like this one don't work.

I need to make a JSONP request because the Blogger API doesn't answer requests from different domains using CORS.

Thank you for your response.

Community
  • 1
  • 1
melanke
  • 804
  • 1
  • 9
  • 25

1 Answers1

7

The Web Worker global has a method called importScripts, which you can use to include script urls.

So just define a callback function, use the function name as the callback url parameter and pass the url to importScripts

webworker.js

function cb(data){
    console.log(data);
}

importScripts('http://example.com/jsonp.php?callback=cb');
Patrick Evans
  • 41,991
  • 6
  • 74
  • 87
  • Thanks a lot! It works! (I've used `self.cb = function (resp) { }`) – melanke Dec 27 '15 at 13:37
  • It looks like as of Chrome 71, runtime calls to `importScripts` are not allowed: "Prior to Chrome 71, calling importScripts() asynchronously outside of the install handler would work. Starting with Chrome 71, those calls throw a runtime exception (unless the same URL was previously imported in an install handler), matching the behavior in other browsers." -- https://developers.google.com/web/updates/2018/10/tweaks-to-addAll-importScripts – Jordan Eldredge Dec 09 '19 at 15:01