ionic webapp browser 下 浏览器返回键事件注册,防止返回跳出
ionic3+Angular 开发webapp生成 浏览器代码,部署到服务器后,将链接挂在微信中访问,发现安卓返回键会直接退出微信的浏览器,体验想当不好, 希望在微信中打开后像app 一样点击返回能 返回上一页或者关闭弹出层。
// An highlighted block
export class MyApp {
rootPage:any;//=TabsPage;
constructor(private _app:App,
private _ionicApp:IonicApp,
private _menu:MenuController,
platform: Platform,
) {
platform.ready().then(() => {
this.setupBackButtonBehavior();
});
}
//返回按钮事件
private setupBackButtonBehavior () {
// If on web version (browser)
// Register browser back button action(s)
window.onpopstate = (evt) => {
// Close menu if open
if (this._menu.isOpen()) {
this._menu.close ();
return;
}
// 关闭弹出层等
let activePortal = this._ionicApp._loadingPortal.getActive() ||
this._ionicApp._modalPortal.getActive() ||
this._ionicApp._toastPortal.getActive() ||
this._ionicApp._overlayPortal.getActive();
if (activePortal) {
activePortal.dismiss();
return;
}
// 当前是否存在 可pop 页面
if (this._app.getActiveNav().canGoBack()){
this._app.getActiveNav().pop();
}else{
// console.info("不能再返回了!!");
}
};
if (window.location.protocol !== "file:") {
// Fake browser history on each view enter
this._app.viewDidEnter.subscribe((app) => {
history.pushState(null, document.title, location.href);
//history.pushState (null, null, "");
});
}
}
}
参考资料_可能需要梯子
链接: https://gist.github.com/t00ts/3542ac4573ffbc73745641fa269326b8
https://github.com/ionic-team/ionic/issues/6363
看到帖子中描述在beta.11 后面提供了 deeplinker 来解决这个问题。
其他方式:
上诉是比较完美的解决了问题, 最开始尝试的是 直接禁用浏览器的返回键,在src/index.html 中添加如下代码
<script>
history.pushState(null, document.title, location.href);
window.addEventListener('popstate', function (event)
{
history.pushState(null, document.title, location.href);
});
window.location.hash="no-back-button";
window.location.hash="Again-No-back-button";//again because google chrome don't insert first hash into history
window.onhashchange=function(){window.location.hash="no-back-button";}
</script>
有更好的办法 也劳烦告知Thx