React js detect page reload - javascript

Using React.js, how I can check if the whole page was reloaded?
if (window.performance) {
console.info("window.performance works fine on this browser");
}
console.info(performance.navigation.type);
if (performance.navigation.type == performance.navigation.TYPE_RELOAD) {
console.info("This page is reloaded");
} else {
console.info("This page is not reloaded");
}
The code above doesn't help, triggers every time I change the component or call any api on the same page.

try this
onUnload(event) {
alert('page Refreshed')
}
componentDidMount() {
window.onbeforeunload = function() {
this.onUnload();
return "";
}.bind(this);
}

Related

React | How to detect Page Refresh (F5)

I'm using React js. I need to detect page refresh. When user hits refresh icon or press F5, I need to find out the event.
I tried with stackoverflow post by using javascript functions
I used javascript function beforeunload still no luck.
onUnload(event) {
alert('page Refreshed')
}
componentDidMount() {
window.addEventListener("beforeunload", this.onUnload)
}
componentWillUnmount() {
window.removeEventListener("beforeunload", this.onUnload)
}
here I have full code on stackblitz
If you're using React Hook, UseEffect you can put the below changes in your component. It worked for me
useEffect(() => {
window.addEventListener("beforeunload", alertUser);
return () => {
window.removeEventListener("beforeunload", alertUser);
};
}, []);
const alertUser = (e) => {
e.preventDefault();
e.returnValue = "";
};
Place this in the constructor:
if (window.performance) {
if (performance.navigation.type == 1) {
alert( "This page is reloaded" );
} else {
alert( "This page is not reloaded");
}
}
It will work, please see this example on stackblitz.
It is actually quite straightforward, this will add the default alert whenever you reload your page.
In this answer you will find:
Default usage
Alert with validation
1. Default Usage
Functional Component
useEffect(() => {
window.onbeforeunload = function() {
return true;
};
return () => {
window.onbeforeunload = null;
};
}, []);
Class Component
componentDidMount(){
window.onbeforeunload = function() {
return true;
};
}
componentDidUnmount(){
window.onbeforeunload = null;
}
2. Alert with validation
You can put validation to only add alert whenever the condition is true.
Functional Component
useEffect(() => {
if (condition) {
window.onbeforeunload = function() {
return true;
};
}
return () => {
window.onbeforeunload = null;
};
}, [condition]);
Class Component
componentDidMount(){
if (condition) {
window.onbeforeunload = function() {
return true;
};
}
}
componentDidUnmount(){
window.onbeforeunload = null;
}
Your code seems to be working just fine, your alert won't work because you aren't stopping the refresh. If you console.log('hello') the output is shown.
UPDATE ---
This should stop the user refreshing but it depends on what you want to happen.
componentDidMount() {
window.onbeforeunload = function() {
this.onUnload();
return "";
}.bind(this);
}
Unfortunately currently accepted answer cannot be more considered as acceptable since performance.navigation.type is deprecated
The newest API for that is experimental ATM.
As a workaround I can only suggest to save some value in redux (or whatever you use) store to indicate state after reload and on first route change update it to indicate that route was changed not because of refresh.
If you are using either REDUX or CONTEXT API then its quite easy. You can check the REDUX or CONTEXT state variables. When the user refreshes the page it reset the CONTEXT or REDUX state and you have to set them manually again. So if they are not set or equal to the initial value which you have given then you can assume that the page is refreshed.

Display warning alert and close session when the browser is closed

The web page is displayed upon redirection from another website and the URL changes during this process to point to a different port number.
So, I would like the JavaScript to detect if the URL is correct.
If the user closes the browser/tab, display an Alert Box with warning message.
Run PHP script to close the user Session
My code is:
if (window.location.href === "http://abc123.net.au:2048 ") {
$(function () {
try {
opera.setOverrideHistoryNavigationMode('compatible');
history.navigationMode = 'compatible';
}
catch (e) {
}
function OnBeforeUnload() {
$(window).onbeforeunload;
// Post to script that will log the user out
xmlhttp.open("POST", "../logscript.php", true);
xmlhttp.send();
}
function ReturnMessage() {
return "Wait, by closing this session I will end your session. You will be required to log in again t access the site.";
}
function UnBindWindow()
{
$(window).unbind('beforeunload', ReturnMessage);
}
$(window).bind('beforeunload', ReturnMessage);
});
}
else {
document.write('<div>code is not working</div>')
}
This is the solution to your second work order:
window.onbeforeunload = bunload;
function bunload() {
dontleave = "Are you sure you want to leave?";
return dontleave;
}

How do I make a JS function that works onolad not work on the first page load.?

I have a html page which has a function that would work once the page loads.
<body onload="startNow()">
This startNow function has a part that refreshes the page if a certain condition is not met and thus causes the function to run again.
function startNow() {
var warning_check = document.getElementsByClassName("warning");
if (warning_check.length == 0) {
checkAll(); //another function call
} else {
window.location.reload();
}
}
Is there a way i can make this startNow function not run the first time this page loads?
Easily done with a localStorage
function startNow(){
var warning_check = document.getElementsByClassName("warning");
if(warning_check.length == 0) {
checkAll(); //another function call
} else {
if (!!localStorage.returningUser){
window.location.reload();
}
}
localStorage.returningUser = 'true';
}
EDIT
the above function still runs for first time users but it won't reload if the code reaches to the reload point. If you want to code to stop running at all then
function startNow(){
if (!localStorage.returningUser){
localStorage.returningUser = 'true';
return false;
}
var warning_check = document.getElementsByClassName("warning");
if(warning_check.length == 0) {
checkAll(); //another function call
} else {
window.location.reload();
}
}

onbeforeunload function having serious issue

I am using native.history.js to put a customised URL in the back button.
The script works fine. Now the issue is I want to make a page redirect when the refresh button is clicked; so i modified the script like this:
<script>
var back = 0;
$(window).bind('beforeunload', function () {
if (confirm('Want to continue?')) {
if (back == 1) {
alert('back');
//window.location.href = "<?=$$last_offer?>";
} else {
alert('refresh');
//window.location.href = "<?=$actual_link;?>";
}
} else {
// Do nothing!
}
});
window.onpageshow = function (e) {
if (e.persisted) {
location.reload();
}
};
window.onpopstate = function (event) {
if (document.location.toString().indexOf("redir=1") > 0) {
back = 1;
window.location.href = "<?=$$last_offer?>";
}
};
</script>
Issue is, the beforeunload function seems not working.
What is the problem I can't fin?.
If I am clicking the back button, the page is taking to the desired page, so it works fine.
All I want is that, somehow the page refresh must work as I anticipated.
Try use
$(window).on('beforeunload', function(){
return 'Are you sure you want to leave?';
});
Instead of bind, use on, i dont know what jquery version you use, but i will suggest "on".
Works fine here:
link
on jquery version 2.x(edge)

Form won't submit in an iframe in a modal window using javascript without returning in Safari

I have a .aspx page that opens a modal window which uses an iframe to load a second .aspx page that creates a form, some text areas and a button that submits the form.
The problem is that in Safari 5 for Windows 7 (and SOMETIMES Chrome) the form doesn't seem to submit unless a return happens.
If CloseModal() happens first, then the page closes without the data being saved.
If return happens first, then the data saves and the window does not close.
Apologies if I'm missing something simple, but any help would be appreciated.
function SubmitFunction()
{
var objForm = document.getElementById("MyForm");
if(objForm.IsValid())
{
objForm.submit();
parent.CloseModal('',1);
return true;
}
else
return false;
}
function CloseModal(ReturnValue,LoadSource,ReturnType)
{
if(window.showModalDialog)
{
window.returnValue = ReturnValue;
if(opener)
{
if(ReturnType == STRING_ARGUMENT_URL && ReturnValue)
{
opener.location.href = ReturnValue;
}
else if(LoadSource)
{
opener.location.reload();
}
}
window.close();
}
else
{
window.returnValue = ReturnValue;
window.close();
}
}
We ended up having to wait until the page reloads and evaluate a variable that is one state by default and another after the form is submitted. I'm still unsure why this was a Safari "only" issue.

Categories

Resources