Android Back Button on a Progressive Web Application closes de App

前端 未结 4 561
栀梦
栀梦 2020-12-07 19:27

Can a \"pure\" HTML5/Javascript (progressive) web application intercept the mobile device back button in order to avoid the App to exit?

This question is similar to

4条回答
  •  没有蜡笔的小新
    2020-12-07 19:56

    i did not want to use native javascript functions to handle this inside of a react app, so i scoured solutions that used react-router or react-dom-router, but in the end, up against a deadline, native js is what got it working. Added the following listeners inside inside componentDidMount() and setting the history to an empty state

    window.addEventListener('load', function() {
      window.history.pushState({}, '')
    })
    
    window.addEventListener('popstate', function() {
      window.history.pushState({}, '')
    })
    

    this worked fine on the browser, but was still not working in the PWA on mobile finally a colleague found out that triggering the history actions via code is what somehow initiated the listeners and voila! everything fell in place

    window.history.pushState(null, null, window.location.href); 
    window.history.back(); 
    window.history.forward(); 
    

提交回复
热议问题