![](/img/trans.png)
[英]How to display customized fancybox when user presses F5 key or clicks browser's back / close button?
[英]Close a modal when user clicks back button in browser React Js
如果用户通过手机访问网站,我将向用户展示一个占据整个屏幕的模式。 用户倾向于本能地单击手机上的后退按钮,而不是使用模式上提供的关闭按钮。
有没有办法拦截用户单击后退按钮时触发的 function? 我想在用户单击手机上的后退按钮时关闭模式,而不是让他们重定向到上一页。
使用历史 API 。 如何实现这一点的一个例子是:
//listen for state changes
window.onpopstate = (event) =>
{
if (!event.state.modalOpened)
{
closeModal()
}
}
//change the actual page state so it contains the modalOpened property
window.history.replaceState({modalOpened: false})
function openModal(content)
{
//push new state, put the modal information in the state object, this will push a new state, when the user presses the back button, the browser will just trigger the onpopstate event, instead of going to the previous page
window.history.replaceState({modalOpened: true})
//this is any code you use to open your modal, for example
ReactDOM.render(<Modal>{content}</Modal>, document.getElementById("moda-container")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.