How can I detect when back button on browser (Chrome, FireFox, Safari etc.) is clicked through JavaScript on my React website and take actions accordingly?
Also, when back button on mobile is pressed, is the event same or similar to when back button in browser is clicked?
Looking forward for an answer. Thanks in advance.
How can I detect when back button on browser (Chrome, FireFox, Safari etc.) is clicked through JavaScript on my React website and take actions accordingly?
Also, when back button on mobile is pressed, is the event same or similar to when back button in browser is clicked?
Looking forward for an answer. Thanks in advance.
Share Improve this question asked May 3, 2021 at 17:02 vaibhav deepvaibhav deep 8454 gold badges14 silver badges32 bronze badges 3- What exactly are you trying to do? Are you going back to somewhere on your own site? There isn't a lot you can actually do here. – Brad Commented May 3, 2021 at 17:07
- Currently the back button takes me to the previous window, I instead want to do something on my site. – vaibhav deep Commented May 3, 2021 at 17:29
- 1 That would be a huge security risk. You won't be able to do that. – R3FL3CT Commented May 3, 2021 at 17:51
3 Answers
Reset to default 1Here is a pretty simple custom hook for that:
const useBackButton = () => {
const [isBack, setIsBack] = useState(false);
const handleEvent = () => {
setIsBack(true);
};
useEffect(() => {
window.addEventListener("popstate", handleEvent);
return () => window.removeEventListener("popstate", handleEvent);
});
return isBack;
};
Working example: https://codesandbox.io/s/cranky-borg-5qwl3?file=/src/index.js
Objective approach:
constructor() {
super();
this.state = {
isBack: false
};
this.onPopstate = this.onPopstate.bind(this)
}
onPopstate() {
this.setState({ isBack: true });
alert("back!!!");
}
ponentDidMount() {
window.addEventListener("popstate", this.onPopstate);
}
ponentWillUnmount() {
window.removeEventListener("popstate", this.onPopstate, false);
}
This works some of the time, but there's no reliable way to detect stuff like this, as of now.
window.addEventListener("beforeunload",function(){
//Checking if the user hasn't clicked on something on the page
if(document.activeElement==document.querySelector("body")){console.log("Back Button Maybe?")}
})
Add these 2 lines into your ponentDidMount().This worked for me
window.history.pushState(null, null, document.URL);
window.addEventListener('popstate', function(event) {
window.location.replace(`YOUR URL`);
});
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742331358a4423784.html
评论列表(0条)