h5---打包APP点击手机返回直接退出app的解决方法

h5打包的app,在android手机上,点击手机自带的物理返回键,直接退出了app。由于onbackPress在app上不生效,于是用js的方式去做了拦截,实现了点击物理返回键返回上一页,而不是退出app。(提示:代码放在main.js文件中,不要乱放)

// android点击手机物理返回键退出app bug解决
document.addEventListener("plusready", function() {
    plus.key.addEventListener('backbutton', function() {
        window.history.go(-1);
     // window.history.back(); },
false); })

参考:https://blog.csdn.net/weixin_42483208/article/details/121231228

//这个不是写在首页,写在子页面(子页面才能返回,写在首页点击返回就是退出)
//不用引入mui.js,都是h5方法
document.addEventListener('plusready', function() {
    var webview = plus.webview.currentWebview();
    plus.key.addEventListener('backbutton', function() {
        webview.canBack(function(e) {
            if(e.canBack) {
                webview.back();
            } else {
                webview.close(); //hide,quit
                //plus.runtime.quit();
            }
        })
    });
});

我的代码,参考:

<!DOCTYPE html><html lang=zh-CN><head><meta charset=utf-8><meta http-equiv=X-UA-Compatible content="IE=edge">
<title>集团</title>
<script>var coverSupport = 'CSS' in window && typeof CSS.supports === 'function' && (CSS.supports('top: env(a)') || CSS.supports('top: constant(a)'))
document.write('<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0' + (coverSupport ? ', viewport-fit=cover' : '') + '" />')</script>
<link rel="stylesheet" href="/static/index.883130ca.css">
</head>
<body style="padding-top:30px;">
<div style="width:100%;height:30px;position:fixed;top:0;left:0;background:#007aff;z-index:1000;"></div>
<noscript><strong>Please enable JavaScript to continue.</strong></noscript>
<div id="app"></div>
<script src="/static/js/chunk-vendors.daecd273.js"></script>
<script src="/static/js/index.b5c1c9e3.js"></script>
<script type="text/javascript">
document.addEventListener('plusready', function() {
    plus.key.addEventListener('backbutton', function() {
        window.history.back();
    });
});
</script>
</body>
</html>

打完收工!

 
posted @ 2025-08-31 23:48  帅到要去报警  阅读(124)  评论(0)    收藏  举报