React - how to open modal when user tries to reload or close window/tab? - javascript

I am trying to trigger a modal when user tries to reload the page, visit new URL or close the browser window/tab.
At the moment, the code is successfully triggering the modal, but a default alert window also pops up which I want to get rid of:
Modal appears below the default alert window (using FireFox)
Code:
componentDidMount() {
window.addEventListener('beforeunload', this.onUnload)
}
componentWillUnmount() {
window.removeEventListener('beforeunload', this.onUnload)
}
onUnload(event) {
event.preventDefault();
this.setState({ modalIsOpen: true })
}

There might be a more recommended way to accomplish this, but overriding the alert function should work:
onUnload(event) {
event.preventDefault();
const nativeAlert = window.alert
window.alert = console.log // Temporarily override the alert function
this.setState({ modalIsOpen: true })
window.alert = nativeAlert // Restore it to default
}

Related

How can i execute a function after a form submission causes a page refresh?

I am using shopify's built in customer create, login, reset form submissions which on submit, forces the page to refresh. My intention is to show a message that shows after the page has been refreshed via a button click function. This is what i have so far; The message shows until that page refreshes and then the active class is removed as you would expect.
$(document).ready(function () {
class Alert {
constructor() {
this.customerAlert = document.createElement('div');
}
init(){
this.customerAlert.classList.add('customer-alert');
document.querySelector('body').append(this.customerAlert);
}
show(message){
this.customerAlert.textContent = message;
this.customerAlert.classList.add('active');
setTimeout(() => {
this.customerAlert.classList.remove('active');
}, 8000);
}
}
//create snackbar and initiate
const alertMessage = new Alert();
alertMessage.init();
const createAccountButton = document.querySelector('input.account-trigger');
createAccountButton.addEventListener('click', () => {
alertMessage.show('Your account in now under review');
});
});
Set a boolean variable in session storage just prior to the submit to represent the two states, and then read it in after the refresh.
Something like this:
function HandleFlag(){
var F=sessionStorage.getItem('Flag');
if(F=='1'){
// display your message box here
sessionStorage.setItem('Flag','0');
} else {
// the state is "0" so toggle it just before submitting
sessionStorage.setItem('Flag','1');
}
}
I hope you get my drift.

How can i handle page refresh event in React.js

I want to make a confirmation before user leaving the page. If he says ok then it would redirect to new page or cancel to leave.
but issue is that when user refresh page using browser refresh btn in google chrome that time below error occur
I tired this code but doesn't work in react.js please help
window.hideWarning = false;
window.addEventListener('beforeunload', (event) => {
if (!window.hideWarning) {
event.preventDefault();
event.returnValue = '';
}
});
Also try this code
window.onbeforeunload = function () { return ''; }.bind(this);
Try this code it's work for me
window.onbeforeunload = function () {
if ("Some condition") {
return '';
}
}.bind(this);
you can also use that
winodow.location.reload(true)
winodow.location.reload(false)
Please use this:
console.log(window.performance.navigation)

BeforeinstallPromt event fired still Add to home screen Prompt not working after setting any value in window.location

Add to Home Screen feature of google is not working after setting any value in window.location.
What has been done so far?
Refer : web-fundamentals-app-install-banners
During this implementation I am capturing the 'beforeInstallPromptEvent' of window and using it later whenever required.
PFB the Code Snippet for the same:
window.addEventListener('beforeinstallprompt', (e) => {
deferredPrompt = e;
// Update UI notify the user they can add to home screen
showInstallPromotion();
});
btnAdd.addEventListener('click', (e) => {
// hide our user interface that shows our A2HS button
btnAdd.style.display = 'none';
// Show the prompt
deferredPrompt.prompt();
// Wait for the user to respond to the prompt
deferredPrompt.userChoice
.then((choiceResult) => {
if (choiceResult.outcome === 'accepted') {
console.log('User accepted the A2HS prompt');
} else {
console.log('User dismissed the A2HS prompt');
}
deferredPrompt = null;
});
});
This above code works perfectly in normal journey but it stopworking as soon as I include something in window.location to go to some app which in install in the device,
When the below code for Truecaller functionality is added in tandem with Add to Home Screen, it stops working:
window.location='xxxxxsdk://some-url/';
I have also tried with other options to redirect to app like location.assign() but still same issue.
Hi) try to put it after the app is installed:
window.addEventListener('appinstalled', function() {
// window.location = ...
});
Here is the doc: https://developer.mozilla.org/en-US/docs/Web/API/Window/appinstalled_event

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.

Identifying X close event of a popup window using javascript

I need to differentiate between user driven close of a popup window using X close button and close through code.
var win= window.showModelessDialog("http://localhost/test/test.aspx",'google,....);
//Some manipulations
//Manipulation ends
if(win!=null && win.open)
{
win.close();
}
Now I have full access over test.aspx and test.aspx.cs.I have a onbeforeunload method defined in test.aspx page which will be called either way I close the window(X close or my code gets executed)I basically want to differentiate my X close and programmatic close so that I can do some backend manipulations
Something like this perhaps:
var MyPopup = {
_win : null,
_userClosingWindow : true,
open : function() {
var _this = this;
this._win = window.open(...);
this._win.onbeforeunload = function() {
if( _this._userClosingWindow ) {
// closed by user
}
else {
// closed in code
}
};
},
close : function() {
this._userClosingWindow = false;
this._win.close();
}
};
Then you can use MyPopup.open() and MyPopup.close() and still know when the close function is called or when the popup is closed by the user.
Use Model Popup & include "OK" & "Cancel" Button.
Now you can handle both the "OK" & "Cancel" Button Events.
you can use:
AjaxControlToolkit - ModalPopup
jQuery UI - Dialog
// parent
function closePopup(win) {
win.close();
// do the magic stuff...
}
// popup (test.aspx)
function closeMe() {
self.opener.closePopup(window);
}
Update
As of your comment, just check the closed property of the popup. If it is false, the popup is still open, otherwise it has already been closed
if (win.closed === false) {
win.close();
// do magic stuff here
}

Categories

Resources