How can I detect closing window angular5 - javascript

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

Related

Bypassing javascript event using another javascript event

I have a button which when click will trigger to open up a popup.
<button id="thisId">OPEN POPUP</button>
The event for it will be something as follow
$(document).on('click', '#thisId', function(){
// DO SOMETHING TO OPEN THE POPUP HERE
});
This button should work as expected if the browser allows popup to be opened on it. Problem is when the popup blocker is enabled. I have quite an amount of buttons like this, probably like nearly 100 buttons with similar thing in the project that i currently working on, and i dont want to do the checking on each of the event handler for each respective buttons. I wanna make a common event handler for all the buttons, which will trigger on click of the button.
So i added another attribute to the same button
<button data-openpopup id="thisId">OPEN POPUP</button>
For this i attach an event specific to this attribute. When the button is clicked, in case if popup blocker is set on for that browser, it will do a checking to check whether popup blocker is on, and if it is, it will throw an alert to the user using jconfirm's alert box. The event for it will be something as follow
$(document).on('click', '[data-openpopup]', function(){
var $this = $(this);
var pop = window.open("about:blank", "new_window_123", "height=150,width=150");
if (!pop || pop.closed || pop.closed == "undefined" || pop == "undefined" || parseInt(pop.innerWidth) == 0 || pop.document.documentElement.clientWidth != 150 || pop.document.documentElement.clientHeight != 150){
pop && pop.close();
// Call jconfirm alert if popup is disabled
$.alert({
title: 'Popup blocked alert!',
content: 'Your popup blocker is currently enabled.',
closeIcon: true,
buttons: {
close: {
text: 'Close',
btnClass: 'btn-blue'
}
}
});
} else {
pop && pop.close();
}
});
Now the issue here is, i want it so that, when click on the button, it will override the original click method which is to open a popup, preventing it from running, and do the popup checking first. If checking is false, then only proceed with the event to open the popup.
So how can i do this?
You could use .stopImmediatePropagation() to prevent the other handler from executing.
But you have to put that in a handler that must be registered before the other(s) since the callbacks are executed in the order the listeners were registered.
If several listeners are attached to the same element for the same event type, they are called in order in which they have been added. If during one such call, event.stopImmediatePropagation() is called, no remaining listeners will be called.
Below, I "simulated" your popup blocker test with an additionnal button... Since it does not seem to be working, at least with AdBlocker Plus (Chrome extention). From what I saw, your condition is always true, AdBlocker active or not.
// To simulate a working blocker detection
var blocker=true;
$("#blockerToggle").on("click",function(){
blocker=!blocker;
$(this).find("span").text(blocker.toString().toUpperCase()).css({"color":(blocker)?"green":"red"});
}).trigger("click");
// Assuming a good popup blocker detection
// This handler can stop the others... Registered AFTER this one.
$(document).on('click', '[data-openpopup]', function(e){
if(blocker){
console.log("Blocker ON! Prevent the other listener(s) from executing.");
e.stopImmediatePropagation();
} else {
console.log("Okay, let the other listener(s) execute.");
}
});
// Other handler
$(document).on('click', '#thisId', function(){
console.log("Other handler executed.");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button data-openpopup id="thisId">OPEN POPUP</button> <button id="blockerToggle">Popup blocker active => <span></span></button>

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

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");
}
}

How do I add jQuery to a submit button which fires before Paypal objects?

I have a Paypal Digital Express form which works fine. However, I would like to add a bit of jQuery to the submit button which will fire -before- the Paypal popup window opens and can prevent the Paypal code from firing. Unfortunately, the Paypal window always open first.
jQuery('#buyLink').click( function(e) {
e.preventDefault();
// if no boxes are checked; no songs selected
if ( jQuery("#buysongs input:checkbox:checked").length == 0) {
alert('Please select at least one song!');
return false;
}
});
Is there a way to prioritise my code so that it fires -before- the Paypal code?
EDIT: I added e.preventDefault() per the first answer, but what that does is:
a) the popup window still opens but
b) the Paypal site is never reached.
Instead, it displays the calling page in the popup.
So... I want to prevent that Paypal popup window from opening. Perhaps I need to change the 'action' on the form and trigger that action from inside my jQuery? If so, how do I do this?
Look into the preventDefault() function:
jQuery('#buyLink').click( function(event) {
event.preventDefault();
if (jQuery("#buysongs input:checkbox:checked").length == 0) {
alert('Please select at least one song!');
return false;
}
else{
// submit form
}
});

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