How to detect the Browser refresh and Close events in Angular JS? - javascript

Hi i have tried the below event to detect but sometimes it doesn't fire the event, while closing the tab or Browser.
$window.onbeforeunload

if you want only browser close do something and you do want when refresh page yuo can use this code:
window.onbeforeunload = function () {
if (performance.navigation.type == 1) {
localStorageService.remove("authorizationData");
}
}

Related

Reload Page on Focus

I have a Progressive Web App that I need to refresh every time the user opens it.
To achieve this I have tried:
1) First Option
window.onblur = function() {
window.onfocus= function () {
window.location = self.location;
}
};
2) Second Option
var blurred = false;
window.onblur = function() {
blurred = true;
};
window.onfocus = function() {
blurred && (window.location = self.location);
};
Credit of Option 1: https://stackoverflow.com/a/16406350/11843328
Credit of Option 2: https://stackoverflow.com/a/11313719/11843328
This work well but the problem is that sometimes whenever you click something, it reloads again. It basically reloads like 4 times in a row with some action. Other times it works as expected, just reloading once, but most of the times is like 4 or 5 times in a row.
I need it to reload just once when opened (on focus). Is there any alternatives I could try or any advice would be appreciated!
Make sure you're using window focus event. As others have pointed out, there is no need to use the blur event, as focus will only fire if the window focus was blurred.
You can use the window.location.reload method to reload the window as well.
window.addEventListener("focus", e => window.location.reload());
<p>Look for a flicker</p>
You don't need the onblur event. Using just the onfocus event will do the work.

How can I detect closing window angular5

I want to delete some data when the user closes the page
I already used beforeunload event but it work only when I refresh the page but when I close it nothing executes.
#HostListener('window:beforeunload', ['$event'])
beforeUnloadHander($event) {
console.log('fdfsdfsd')
if(!this.accepted && this.details.length != 0){
this.bookingService.deleteRequest(this.details[3]);
}
}
if there's any other method can I use it
I'm using Angular 5

Can we detect browsers refresh and back button events?

Anybody know how to detect browsers refresh and back button events in firefox using jquery or javascript.
For back button:
window.addEventListener('popstate', function (event) {
//Your code here
});
For Refresh:
window.onbeforeunload = function () {
// Your code here
}
You can try WindowEventHandlers.onbeforeunload:
window.onbeforeunload = function(e) {
};
and
$(window).unload(function() {
//
});
Also check Browser Back Button Detection:
I have made a very reusable javascript class, that can be simply
dropped into your web page, and when the user clicks back, it will
call a function. The default function on this call is a javascript
alert “Back Button Clicked”.
To replace this functionality, you simply need to override the OnBack
function. This can be done by using the code below.
<script type="text/javascript">
bajb_backdetect.OnBack = function()
{
alert('You clicked it!');
}
</script>
This will now replace the “Back Button Clicked” alert with a “You
clicked it!’” alert.
Check this page: Manipulating the browser history
You can probably get something working with using history.pushState and window.onpopstate
You can use the following events:
window.onpopstate for back button press.
window.onpopstate = (e) => {
// your logic goes here
};
window.onbeforeunload for refresh or tab close.
window.onbeforeunload = (e) => {
// your logic here
e.preventDefault();
e.returnValue = 'There are unsaved changes. Sure you want to leave?';
};

Phonegap backbutton event, detect first page in history?

Adding a backbutton event listener to my Phonegap 2.0 mobile app prevents the user from exiting using the back key.
Before adding the event listener this was working: if the user visited N pages and clicked back N+1 times, the app would close (or go in the background for android 4.0 or higher).
Please see my code bellow.
document.addEventListener("backbutton", function(){
if (window.history.length == 0) { // this does not work
function quitApp(){
navigator.app.exitApp();
}
navigator.notification.confirm(
"Are you sure you want to quit?",
quitApp,
'App Title',
'Cancel,Ok');
return;
}
if (typeof(window.activePage.onBack) === 'function') {
window.activePage.onBack();
} else {
window.history.back();
}
}, false);
Any idea how i can achieve this: allow the user to exit using the back button while keeping my event listener?
Thanks!
Try to bind the back button on your title page, maybe something like this:
$('#home-page-title').bind( 'pageinit',function(event){
document.addEventListener("backbutton", function(){
navigator.app.exitApp();
}, false);
});

window.beforeunload called twice in Firefox - how to get around this?

I'm creating a popup window that has a beforeunload handler installed. When the "Close" file menu item is used to close the popup, the beforeunload handler is called twice, resulting in two "Are you sure you want to close this window?" messages appearing.
This is a bug with Firefox, and I've reported it here, but I still would like a way to prevent this from happening. Can you think of a sane way of detecting double beforeunload to prevent the double message problem? The problem is that Firefox doesn't tell me which button in the dialog the user elected to click - OK or cancel.
<script type="text/javascript">
var onBeforeUnloadFired = false;
window.onbeforeunload = function ()
{
if (!onBeforeUnloadFired) {
onBeforeUnloadFired = true;
event.returnValue = "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?";
}
window.setTimeout("ResetOnBeforeUnloadFired()", 10);
}
function ResetOnBeforeUnloadFired() {
onBeforeUnloadFired = false;
}
</script>
Set a variable in the handler to prevent the dialog coming up the second time. Use setTimeout to reset it afterwards.
This is definitely a FF bug. I've reported it at https://bugzilla.mozilla.org/show_bug.cgi?id=531199
The best solution I've found is to use a flag global variable that is reset after so many milliseconds, say 500 (this ensures that the function can be called again, but not immediately after its appearance).
See last code in:
http://social.msdn.microsoft.com/Forums/en/sharepointinfopath/thread/13000cd8-5c50-4260-a0d2-bc404764966d
I've found this problem in Chrome 21, Firefox 14, IE 7-9, Safari 5 (on PC).
The following works on all of these browsers. If one removes the window.onbeforeunload function during the event this will prevent the second call. The trick is to reset the window.onbeforeunload function if the user decides to stay on the page.
var window_on_before_unload = function(e) {
var msg;
// Do here what you ever you need to do
msg = "Message for user";
// Prevent next "window.onbeforeunload" from re-running this code.
// Ensure that if the user decides to stay on the page that
// this code is run the next time the user tries to leave the page.
window.onbeforeunload = set_on_before_unload;
// Prepare message for user
if (msg) {
if (/irefox\/([4-9]|1\d+)/.test(navigator.userAgent))
alert(msg
+ '\n\nThe next dialog will allow you to stay here or continue\nSee Firefox bug #588292');
(e = e || window.event).returnValue = msg;
return msg;
}
};
// Set window.onbeforeunload to the above handler.
// #uses window_on_before_unload
// #param {Event} e
var set_on_before_unload = function(e) {
// Initialize the handler for window.onbeforeunload.
window.onbeforeunload = window_on_before_unload;
}
// Initialize the handler for window.onbeforeunload.
set_on_before_unload();
Create a global variable that is set to true inside the handler. Only show the alert/popup when this variable is false.
I use the following snippet to track the exitcount
When the page loads the following variable exitCount is initialized
if (typeof(MTG) == 'undefined') MTG = {};
MTG.exitCount=0;
and in the Window unload event
$(window).bind("beforeunload", function(){
if (MTG.exitCount<=0)
{
//do your thing, save etc
}
MTG.exitCount++;
});
I've found that instead of doing your own call to confirm(), just do even.preventDefault(); within the beforeunload event. Firefox throws up its own confirm dialog.
I'm not sure if this is the correct/standard thing to do, but that's how they're doing it.
I have a document opening another popup window with window.open. In the original window I have registered (with jquery) a listener for "unload" event like this:
var popup_window = window.open(...)
$(popup_window).on('unload', function(event) ...
I have came across this page because the event was effectively triggering twice. What I have found is that it is not a bug, it triggers twice because it fires once for "about:blank" page being replaced by your page and another for your page being unloaded.
All I have to do is to filter the event that I am interested in by querying the original event:
function (event) {
var original_url = e.originalEvent.originalTarget.URL;
if (original_url != 'about:blank')
{
... do cool things ...
}
}
I don't know if this applies to the original question, because it is a special case of a window opening another, but I hope it helps.

Categories