简体   繁体   English

未为在 SPA 上创建的 PWA 调用“beforeinstallprompt”事件

[英]'beforeinstallprompt' event not called for the PWA created on a SPA

I have a SPA say https://www.example.com .我有一个 SPA 说https://www.example.com And one of the sub-pages https://www.example.com/foo can be added as a PWA.并且可以将子页面https://www.example.com/foo添加为 PWA。 On navigating to /foo from the homepage, the manifest and service-worker get installed and registered correctly and the PWA can be installed from the A2HS native buttons too, but the event beforeinstallprompt isn't called on chrome.从主页导航到/foo时,manifest 和 service-worker 已正确安装和注册,并且 PWA 也可以从 A2HS 本机按钮安装,但在 chrome 上不会调用beforeinstallprompt事件。 If the page /foo is refreshed then the event is called.如果页面/foo被刷新,则调用该事件。 It's only when the navigation happens to it from another page that isn't in the scope of the PWA.仅当从不在 PWA 的 scope 中的另一个页面发生导航时。 The lighthouse audit passes all tests on /foo as well.灯塔审计也通过了/foo上的所有测试。 Has anyone tried creating multiple PWAs on a SPA, or encountered a similar issue?有没有人尝试在 SPA 上创建多个 PWA,或者遇到过类似的问题?

I don't think this is a good solution, but this is how I got around it on my Gatsby.js site:我认为这不是一个好的解决方案,但这就是我在 Gatsby.js 网站上解决它的方法:

  1. On every page (even those where I don't have the "Add to Homepage" custom trigger), I listen for the beforeinstallprompt event.每个页面上(即使是那些我没有“添加到主页”自定义触发器的页面),我都会监听beforeinstallprompt事件。
  2. I set up a listener for a custom event on the <html> element on the pages that have my "Add to Homepage" custom trigger.我为具有“添加到主页”自定义触发器的页面上的<html>元素上的自定义事件设置了一个侦听器。
  3. When beforeinstallprompt fires, I stash a reference to the event on the <html> tag (this does not get swapped out in between pages for my SPA) using jQuery's $.data() - I couldn't get vanilla JavaScript dataset to work but I may have been using it wrong, and I had jQuery loaded in anyway.beforeinstallprompt触发时,我使用 jQuery 的$.data()<html>标记上存储对事件的引用(这不会在我的 SPA 页面之间换出) - 我无法让 vanilla JavaScript dataset工作,但是我可能用错了,无论如何我都加载了 jQuery。
  4. In the beforeinstallprompt handler, after setting the data, I fire the custom event on the <html> element.beforeinstallprompt处理程序中,设置数据后,我在<html>元素上触发自定义事件。
  5. The page that has the "Add to Homepage" custom trigger catches this custom event, grabs the reference to the beforeinstallprompt event from the $( 'html ').data( 'event' ) and carries on with it as normal.具有“添加到主页”自定义触发器的页面捕获此自定义事件,从$( 'html ').data( 'event' )中获取对beforeinstallprompt事件的引用并照常进行。

Hopefully that helps;希望这会有所帮助; it feels pretty hacky but I'm pretty new to PWAs / SPAs / React!感觉很老套,但我对 PWA/SPA/React 还是很陌生!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM