我必须在 React js 上的浏览器返回事件上显示警报。我曾尝试使用 ,addEventListener但我不确定将代码放置在 React 页面中的何处。我应该放置在任何生命周期钩子中还是在渲染中?我不确定。请帮帮我。
在react js 上显示浏览器后退按钮事件的警报
IT技术
reactjs
2021-05-14 16:09:50
4个回答
如果您使用react-hooks,您可以使用 useEffect 钩子在以下步骤中完成
import React, { useState, useEffect } from "react";
const [finishStatus, setfinishStatus] = useState(false);
const onBackButtonEvent = (e) => {
e.preventDefault();
if (!finishStatus) {
if (window.confirm("Do you want to go back ?")) {
setfinishStatus(true)
// your logic
props.history.push("/");
} else {
window.history.pushState(null, null, window.location.pathname);
setfinishStatus(false)
}
}
}
useEffect(() => {
window.history.pushState(null, null, window.location.pathname);
window.addEventListener('popstate', onBackButtonEvent);
return () => {
window.removeEventListener('popstate', onBackButtonEvent);
};
}, []);
你可以试试这个
window.addEventListener('popstate', (event) => {
alert("You message");
});
您可以将其放入componentWillMount()或componentDidMount()根据需要放置。
查看此链接如何检测浏览器后退按钮事件 - 跨浏览器
那里的关键点:
document.onmouseover = function() {
//User's mouse is inside the page.
window.innerDocClick = true;
}
document.onmouseleave = function() {
//User's mouse has left the page.
window.innerDocClick = false;
}
window.onhashchange = function() {
if (window.innerDocClick) {
//Your own in-page mechanism triggered the hash change
} else {
//Browser back button was clicked
}
}
这可以防止使用后退空间向后导航
$(function(){
/*
* this swallows backspace keys on any non-input element.
* stops backspace -> back
*/
var rx = /INPUT|SELECT|TEXTAREA/i;
$(document).bind("keydown keypress", function(e){
if( e.which == 8 ){ // 8 == backspace
if(!rx.test(e.target.tagName) || e.target.disabled || e.target.readOnly ){
e.preventDefault();
}
}
});
});
最后我自己解决了。我已经用下面的代码给出了解释:
首先,在任一componentDidUpdate或componentWillMount钩子中添加以下代码:
window.history.pushState({name: "browserBack"}, "on browser back click", window.location.href);
window.history.pushState({name: "browserBack"}, "on browser back click", window.location.href);
我推送它两次的原因是只有在推送两次时状态才会更新。这是Ref。上面的代码将在页面加载的历史记录中推送当前页面的 URL。
因此,当单击后退浏览器按钮时,同一页面将再次重新加载,因为该pushState方法已操纵了历史记录。
然后在pushState方法上方添加以下代码:
window.addEventListener('popstate', (event) => {
if (event.state) {
//do your code here
}
}, false);
现在,当单击浏览器后退按钮时,上面的偶数侦听器将被调用,并且由于我们更新了statewhichpushState方法,the ifwill be true 并且您可以在其中做任何您想做的事情。