处理打字稿中的浏览器后退按钮事件 [英] Handle browser back button events in typescript
本文介绍了处理打字稿中的浏览器后退按钮事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一篇文章的代码.
window.addEventListener('popstate', function (event) {
// The popstate event is fired each time when the current history entry changes.
var r = confirm("You pressed a Back button! Are you sure?!");
if (r == true) {
// Call Back button programmatically as per user confirmation.
history.back();
// Uncomment below line to redirect to the previous page instead.
// window.location = document.referrer // Note: IE11 is not supporting this.
} else {
// Stay on the current page.
history.pushState(null, null, window.location.pathname);
}
history.pushState(null, null, window.location.pathname);
}, false);
该代码在哪里放置在角度2的组件中?上面的代码打字稿兼容吗?截至目前,当我按下后退"按钮时,我无法触发此事件.有什么更好的方法吗?
where do i put this code in component in angular 2? is above code typescript compatible? I am not able to fire this event when i press back button as of now. is there any better way?
推荐答案
在angular 2中,您可以使用具有onPopState
侦听器的PlatformLocation
.
In angular 2 you can use PlatformLocation
which has onPopState
listener.
import { PlatformLocation } from '@angular/common'
constructor(location: PlatformLocation) {
location.onPopState(() => {
var r = confirm("You pressed a Back button! Are you sure?!");
if (r == true) {
// Call Back button programmatically as per user confirmation.
history.back();
// Uncomment below line to redirect to the previous page instead.
// window.location = document.referrer // Note: IE11 is not supporting this.
} else {
// Stay on the current page.
history.pushState(null, null, window.location.pathname);
}
history.pushState(null, null, window.location.pathname);
});
}
这篇关于处理打字稿中的浏览器后退按钮事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文