LoginSignup
1
3

More than 5 years have passed since last update.

LaravelのプロジェクトにAdd to homescreenを実装してみた

Last updated at Posted at 2018-12-17

GameWith Advent Calendar 2018

この記事はGameWith Advent Calendar 2018 の18日目になります!

はじめに

自分で作ったサイトに勉強を兼ねてAdd to homescreenを実装しました。

AndroidやWindowsで最新Chromeであればこのようにデスクトップに追加できます。

https://www.holy-place-photo.com/にアクセスをし、右側の三点リーダーから『「Holy Place Photo」インストールしています』をクリックします。

1.PNG

バナーが表示されるので「インストール」をクリックします。

2.PNG

クリックするとブラウザではなく単独のアプリケーションとしてHoly Place Photoが起動します。

3.PNG

単独のアプリケーションなのでデスクトップにアイコンができ、タスクバーにも表示されます。

4.PNG

また、Chromeのアプリ一覧にも表示されます。

5.PNG

削除するときはChromeのアプリ一覧から右クリックをし、「Chromeから削除...」をクリックすることで、削除できます。

6.PNG

実装

manifest.json

まずはAdd to homescreenの肝であるmanifest.json。

public直下に置いています。

また、auncher-144x144.pngとlauncher-512x512.pngもpublic直下に置いてます。

manifest.json
{
  "short_name": "HPP",
  "name": "Holy Place Photo",
  "icons": [
    {
      "src": "launcher-144x144.png",
      "type": "image/png",
      "sizes": "144x144"
    },
    {
      "src": "launcher-512x512.png",
      "type": "image/png",
      "sizes": "512x512"
    }
  ],
  "background_color": "#fff",
  "theme_color": "#e1e4e8",
  "orientation": "portrait",
  "start_url": "/",
  "display": "standalone"
}

HTML

作成したmanifest.jsonはlinkタグで読み込みます。

<link rel="manifest" href="/manifest.json">

service worker

fetchを書かないと動かないそうです(空でよい)

public直下に置きます。

sw.js
self.addEventListener('install', (e) => {
  console.log('ServiceWorker install')
});

self.addEventListener('fetch', (e) => {
});

JavaScript

上記に書かれているsw.jsを読み込んでいます。

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw.js').then( (registration) => {
    // 登録成功
    console.log('ServiceWorker registration successful with scope: ', registration.scope);
  }).catch((err) => {
    // 登録失敗 :(
    console.log('ServiceWorker registration failed: ', err);
  });
}

デバッグ

Chromeであれば開発者ツールのApplicationのManifestの「Add to homescreen」からテストができます。

※ただし、localhost or httpsでアクセスしているときのみ

スクリーンショット 2018-12-18 0.33.25.png

おわりに

コピペで簡単に実装できますが、デスクトップアプリケーションになったことで、デメリットもあります(単独のアプリケーションで動くので、検索したいときにChromeに切り替えたりなど)

HTML5でのセッションでも、プロダクトにはUIUX設計をしてから入れるべきと会話されていました。

それでも新しい技術使いたい気持ちもわかる

次はオフラインキャッシュ実装してみようと思います!

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