LoginSignup
2
0

More than 5 years have passed since last update.

Dart で PWA (4) Requestイベントをフックして独自処理

Last updated at Posted at 2018-12-08

前回の続きです。

Index
(1) Hello World PWA
(2) Add to Home
(3) Standard Web Notification
(4) Hook request and Do original processing
(5) Post message

Code
https://github.com/kyorohiro/memo_pwa_2018

今回は、Requestイベントをフックして独自の処理を追加してみます。

Requestに応じてResponseを生成できるので、
やろうと思えば、 MVCフレームワーク的なものを ServiceWorker で完結することも可能でしょう。

ServiceWorker

書いている通りですが、PWAを実現している、オフライン化、Push通知などは、 ServiceWorker の機能です。

ServiceWorker は、 イベントドリブンな Worker ということで良いと思います。
https://developer.mozilla.org/en-US/docs/Web/API/Worker

Requestイベントをフックして独自処理

[1] サービスワーカーを追加するだけのスイクリプトを書く

main.dart
import 'package:service_worker/window.dart' as sw;

void main() {
  if(!sw.isSupported) {
    print(">> service worker is not support ");
    return;
  }
  print(">> service worker is support ");
  sw.register("sw.dart.js");
}

[2] Requestをフックする ServiceWorker を書く

sw.dart
import 'package:service_worker/worker.dart' as sw;

void main() {
  sw.onInstall.listen((sw.InstallEvent e){
    print("#>>on install");
    e.waitUntil(sw.skipWaiting());
  });

  sw.onFetch.listen((sw.FetchEvent e) {
    print("##>> fetch");
    Future<sw.Response> responseTask = new Future(() async {
      String path = e.request.url.replaceFirst(RegExp(r"(http|https)://[^/]*"), "");
      return new sw.Response.custom("### ${path}",status: 200,statusText: "OK");
    });
    e.respondWith(responseTask);
  });
}

確認

webdev serve --release

として、サーバーを起動したあと、ブラウザーでアクセスすると

スクリーンショット 2018-12-09 0.32.37.png

Reload すると

スクリーンショット 2018-12-09 0.30.43.png

Request の Path を表示できます。

ref

2018年12月の時点の、動くように改造した物を、以下に起きましたしました。
https://github.com/kyorohiro/memo_pwa_2018
https://github.com/kyorohiro/pwa
https://github.com/kyorohiro/service_worker

PS

https://github.com/isoos/pwa が masterブランチで、
一部、動かなかったので、フォークして修正しています。
https://github.com/kyorohiro/pwa

今回は、修正したものを使用しています。

次回

Notification とか ServiceWorker とか、
Dart で 実現する方法を紹介していきいます。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0