javascript PWA清单start_url作为current_url

8ulbf1ek  于 5个月前  发布在  Java
关注(0)|答案(2)|浏览(73)

我有一个渐进式Web应用程序(PWA).在我有一个manifest.json.我想设置清单的start_url为当前URL.有没有什么办法设置start_url为当前URL,当安装应用程序?
注意:-在我的PWA i中,每个用户都有一个唯一的帐户URL。所以当他们安装PWA时,start_url应该是他们的current_url(例如:https://example.com/user/id=abc1322112
我尝试使用script.js更改清单。没有任何效果。

nzrxty8p

nzrxty8p1#

您不能更改清单中的URL,但可以将其设置为服务工作线程将重定向的假URL。
清单:

{
  "start_url": "/user/me"
}

字符串
服务人员:

self.addEventListener("fetch", event => {
  const url = new URL(event.request.url);
  if (url.pathname === "/user/me") {
    const userId = /* get user id here */;
    const newUrl = `/user/id=${userId}`;
    // Redirect to the correct url
    const response = new Response(null, { status: 302, headers: { Location: newUrl } });
  } else {
    // In all other cases, just fetch from the network
    event.respondWith(fetch(event.request));
  }
});

mlnl4t2r

mlnl4t2r2#

<script>
const manifest = {
  name: 'My App',
  short_name: 'My App',
  display: 'standalone',
  theme_color: '#ffffff',
  background_color: '#ffffff',
  icons: [
    { src: `${window.location.origin}/icon-192x192.png`, sizes: '192x192', type: 'image/png' },
  ],
  start_url: window.location.href
};
const link = document.createElement('link');
link.rel = 'manifest';
link.href = `data:application/json;base64,${btoa(JSON.stringify(manifest))}`;
document.head.appendChild(link);
</script>

字符串
如果有人需要的话,这个剧本就行了。
删除你的manifest.json并将此scipt放入你的JS或HTML中。将你的图标替换为“icon-192x192.png”

相关问题