3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

webpushをやってみた

Posted at

やりたいこと

webpushを使い通知を出したい。(rssの代わり)

やること

JavaScript Firebase Cloud Messagingを使い静的サイトに通知する仕組みを埋め込む

やったこと

JavaScript Firebase Cloud Messagingを使い静的サイトに通知する仕組みを埋め込む

公式ページの動画を見ながら埋め込み
https://firebase.google.com/docs/cloud-messaging/js/client?hl=ja
いろんな記事見たりしてやったがエラー出たりでこの動画が一番わかりやすかった。

index.html
<script src="https://www.gstatic.com/firebasejs/7.14.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.14.1/firebase-messaging.js"></script>
<script>
  // Your web app's Firebase configuration
  var firebaseConfig = {
  // 省略
  };
  // Initialize Firebase
  firebase.initializeApp(firebaseConfig);
</script>
<script>
  const messaging = firebase.messaging();
  console.log(messaging.requestPermission());
  messaging.usePublicVapidKey("省略");
  messaging.requestPermission()
    .then(function(){
      console.log('have');
      return messaging.getToken();
    })
    .then(function(token){
      console.log(token);
    })
    .catch(function(err){
      console.log('error');
    });
</script>

ちょっと変えた部分は
<script src="https://www.gstatic.com/firebasejs/7.14.1/firebase-messaging.js"></script>を入れないとmessaging()が動きません。

firebase-messaging-sw.js

importScripts("https://www.gstatic.com/firebasejs/7.14.1/firebase-app.js");
importScripts("https://www.gstatic.com/firebasejs/7.14.1/firebase-messaging.js");
// Your web app's Firebase configuration
var firebaseConfig = {
  // 省略
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();

firebaseはfirebase-messaging-sw.jsのファイル名のものを読みに行くようなので、ファイルを置き
importScriptsを使ってindex.htmlと同じように呼び出して上げると裏側でも動くようになります。

あとはCloud Messaging管理画面でメッセージを作成し通知

通知はコマンドでもできます。
ゆくゆくは更新とともに通知を自動化したいなーと

3
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
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?