最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use Service Workers in Google Chrome extensions to modify an HTTP response body? - Stack Overflow

programmeradmin0浏览0评论

Now that Google Chrome extensions can register Service Workers, how can I use them in order to modify HTTP responses from all hosts, e.g. by replacing all occurrences of cat with dog?

Below is a sample code from Craig Russell, but how to use it inside Chrome extensions and bind it to all hosts?

self.addEventListener('fetch', function(event) {
    event.respondWith(
        fetch(event.request).then(function(response) {
            var init = {
                status:     response.status,
                statusText: response.statusText,
                headers:    {'X-Foo': 'My Custom Header'}
            };
            response.headers.forEach(function(v,k) {
                init.headers[k] = v;
            });
            return response.text().then(function(body) {
                return new Response(body.replace(/cat/g, 'dog'), init);
            });
        })
    );
});

Now that Google Chrome extensions can register Service Workers, how can I use them in order to modify HTTP responses from all hosts, e.g. by replacing all occurrences of cat with dog?

Below is a sample code from Craig Russell, but how to use it inside Chrome extensions and bind it to all hosts?

self.addEventListener('fetch', function(event) {
    event.respondWith(
        fetch(event.request).then(function(response) {
            var init = {
                status:     response.status,
                statusText: response.statusText,
                headers:    {'X-Foo': 'My Custom Header'}
            };
            response.headers.forEach(function(v,k) {
                init.headers[k] = v;
            });
            return response.text().then(function(body) {
                return new Response(body.replace(/cat/g, 'dog'), init);
            });
        })
    );
});
Share Improve this question edited Oct 13, 2017 at 6:22 Pacerier 89.9k111 gold badges385 silver badges645 bronze badges asked Dec 27, 2016 at 18:25 niutechniutech 30k15 gold badges101 silver badges109 bronze badges 5
  • Can't seem to work, I'm getting error Add/AddAll does not support schemes other than "http" or "https" on caches cache.addAll(urlsToCache) – Pacerier Commented Sep 17, 2017 at 19:24
  • Many results here: google./search?q=cache.addAll but not one tutorial seem to be for Chrome Extension... – Pacerier Commented Oct 13, 2017 at 6:34
  • ⨕ The chrome object in serviceworker is all weird. chrome.tabs not possible. – Pacerier Commented Oct 13, 2017 at 7:28
  • Ok after some trial and error I've got it partially pieced. I've posted an answer, see below. ¶ Btw I don't think that cache is a required API here. – Pacerier Commented Oct 13, 2017 at 10:23
  • For crossorigin serviceworker see stackoverflow./q/46760820/632951 – Pacerier Commented Oct 15, 2017 at 22:58
Add a ment  | 

1 Answer 1

Reset to default 1

Solution

≪manifest.json≫:

{"manifest_version":2,"name":"","version":"0","background":{"scripts":["asd"]}}

≪asd≫:

navigator.serviceWorker.register('sdf.js').then(x=>console.log('done', x))

≪sdf.js≫:

addEventListener('fetch', e=> e.respondWith(fetch/*btw xhr is undefined*/(e.request).then(r=>{
  if(r.headers === undefined /*request not end with <.htm>, <.html>*/){}else{
    console.assert(r.headers.get('content-type')===null)/*for some odd reason this is empty*///[
      let h = new Headers()
      r.headers.forEach((v,k)=>h.append(k,v))
      Object.defineProperty(r,'headers',{'writable':true})
      r.headers = h
      r.headers.append('content-type','text/html'/*btw <htm> doesnt work*/)
    //]
  }
  return r.text().then(_=>new Response(_.replace(/cat/g,'dog'),r))
})))

Go to ≪page url≫ (≪chrome-extension://≪ext id≫/≪page path≫≫) and see the replacements.


Standalone response

≪manifest.json≫ and ≪asd≫ same as above.

≪sdf.js≫:

addEventListener('fetch', e=> e.respondWith(new Response('url: '+e.request.url,{headers:{'content-type':'text/html'/*, etc*/}})))


Btw

Serviceworker has other events that can be delved into eg:

addEventListener('message', e=>{
  console.log('onmessage', e)
})
addEventListener('activate', e=>{
  console.log('onactivate', e)
})
addEventListener('install', e=>{
  console.log('oninstall', e)
})


Alternatives

Note that currently serviceworker [–cf webNavigation, webRequest] is the only way to do this because some lamer in Google development team has decided that its "insecure" for response-modifying webNavigation and webRequest.


Note

Chrome bugs:

  • Extension ≪Reload≫ will not reload serviceworkers. You need to remove the extension and load it back in.
  • Page refresh does not refresh, even with chrome devtools disable cache hard reload. Use normal page visit.
发布评论

评论列表(0)

  1. 暂无评论