为博客园加上PWA支持

发布时间 2023-04-06 15:50:58作者: 海边星

由于缺乏一些参数,我的博客首页,通过iOS的Safari浏览器“添加到主屏幕”时,会以“浏览器网页”的形式打开。
我想把博客首页固定到主屏幕上,以PWA App的形式打开,所以有了这篇随笔。

通过参考 iOS 如何添加网页到主屏幕可以全屏打开,可以了解到只需要在网页的head内添加以下标签即可粗略达成目标:

<meta name="apple-mobile-web-app-capable" content="yes">

当然,这样的用户体验不会很好,因为没有指定主屏幕的图标,地址栏也是黑色的。所以完善上面的标签,来达成 通知栏为白色、有主屏幕图标(格式须为png),点击博文也不会出现地址栏 这些需求。

<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="theme-color" content="#fff">
<link rel="apple-touch-icon" sizes="180x180" href="https://files.cnblogs.com/files/StarsbySea/apple-touch-icon.ico">
<link rel="manifest" href="https://files-cdn.cnblogs.com/files/StarsbySea/manifest.json">

然后让ChatGPT完成以上需求,生成了如下的代码:

<script>
  function addMetaTagsAndLinks() {
    // 添加适配iOS PWA模式的meta标签
    const appleWebAppMetaTag = document.createElement('meta');
    appleWebAppMetaTag.name = 'apple-mobile-web-app-capable';
    appleWebAppMetaTag.content = 'yes';
    document.head.appendChild(appleWebAppMetaTag);

    // 添加主题颜色meta标签
    const themeColorMetaTag = document.createElement('meta');
    themeColorMetaTag.name = 'theme-color';
    themeColorMetaTag.content = '#fff';
    document.head.appendChild(themeColorMetaTag);

    // 添加Apple Touch图标
    const appleTouchIconLink = document.createElement('link');
    appleTouchIconLink.rel = 'apple-touch-icon';
    appleTouchIconLink.sizes = '180x180';
    appleTouchIconLink.href = 'https://files.cnblogs.com/files/StarsbySea/apple-touch-icon.ico';
    document.head.appendChild(appleTouchIconLink);

    // 添加iPhone 14启动画面
    const iPhoneXRSplashLink = document.createElement('link');
    iPhoneXRSplashLink.href = 'https://files.cnblogs.com/files/StarsbySea/apple-splash-1170-2532.ico';
    iPhoneXRSplashLink.media = '(device-width: 390px) and (device-height: 844px) and (-webkit-device-pixel-ratio: 3) and (orientation: portrait)';
    iPhoneXRSplashLink.rel = 'apple-touch-startup-image';
    document.head.appendChild(iPhoneXRSplashLink);

    // 添加Manifest
    const manifestLink = document.createElement('link');
    manifestLink.rel = 'manifest';
    manifestLink.href = 'https://files-cdn.cnblogs.com/files/StarsbySea/manifest.json';
    document.head.appendChild(manifestLink);
  }

  // Call the function immediately after its definition
  (function() {
    addMetaTagsAndLinks();
  })();
</script>

把以上代码添加到管理后台-设置中的的“页首 HTML 代码”中就可以了。