How can i check page is going to refresh in "beforeunload" event in angular5 - angular5

i am trying to put logic when user close the browser/tab then i need to clear the local session. so i have used beforeunload event. The problem is that it's getting called on both browser close as well as on page refresh. and i don't have to clear session on refresh it should be on close.
i tried to check only by using clientY and pageY but it's not working for me.
also i tried with the below code to identify browser is going to refresh or not and set the flag value and use it in beforeunload event. but it's getting called after beforeunload event
this.subscription = this.router.events.subscribe((event) => {
if (event instanceof NavigationStart) {
this.browserRefresh = !this.router.navigated;
if(this.browserRefresh)
{
console.log("browserRefresh");
}
else
{
console.log(" else browserRefresh");
}
}
});
#HostListener('window:beforeunload', ['$event'])
beforeunload($event) {
console.log("clear session");
}
Please suggest if i am using wrong event for the task or suggest me the correct way to this. i checked few links suggested but nothing is helping.
Thanks

You can try like this Hope so it can work
#HostListener('window:unload', ['$event'])
beforeunload($event) {
console.log("clear session");
}

Related

How to start `mockjax` back after `stop`

In my application I have a shuffle button to start and stop the mockjax response. as a first time, I am initiating the mockjax it works. later the user click on off button to stop mockjax service. ( I am showing server data )
for stop I use:
stopSimulation : function( ) {
if( !this.retriveSimulationStatus() ) {
console.log("i switched off!!");
$.mockjax.clear(); //removes the simulation;
}
}
But user clicks back to start button, But mockjax not intercepting again to provide the data.
so what is the correct way to stop and start the mockjax service? any one help me?
Clearing the Mockjax handlers does NOT "stop" them, it erases them from Mockjax. There is no "start"/"stop" functionality. You will need to clear the handlers, then re-add the handlers when you want to start. Here's an example:
var handler = { url: '/foo', responseText: { foo: 'bar' } };
function start() {
$.mockjax(handler);
}
function stop() {
$.mockjax.clear();
}

Openerp "Save" button persists even after confirming the PO

I am not sure whether I broke the flow and introduced this bug. When I am editing a PO and confirming the PO (see Fig 2).
The changes get updated in database however the save button is still there. But the PO gets confirmed (See fig 3).
I need the save button to be replaced with "Edit" button (By default it was like that).
Can anyone suggest What could be wrong or any settings stuff??
Any help is appreciated..
In web addons-->web-static-src-->js-->view_form.js
add below lines of code:
on_button_save: function() {
var self = this;
var result = confirm("Do you want to save Record..?");
if (result==true) {
return this.save().done(function(result) {
self.trigger("save", result);
self.reload().then(function() {
self.to_view_mode();
var parent = self.ViewManager.ActionManager.getParent();
if(parent){
parent.menu.do_reload_needaction();
}
});
});
}
else{
return result;
}
},
This is the default behaviour to have the save button appear as it is if you did not click it and you clicked the button on the form.
Actually i written this code for my requirement.Before saving the record should ask the conformation to save.this code may help full you to further implements ion of you are requirement.

How do you poll for a condition in Intern / Leadfoot (not browser / client side)?

I'm trying to verify that an account was created successfully, but after clicking the submit button, I need to wait until the next page has loaded and verify that the user ended up at the correct URL.
I'm using pollUntil to check the URL client side, but that results in Detected a page unload event; script execution does not work across page loads. in Safari at least. I can add a sleep, but I was wondering if there is a better way.
Questions:
How can you poll on something like this.remote.getCurrentUrl()? Basically I want to do something like this.remote.waitForCurrentUrlToEqual(...), but I'm also curious how to poll on anything from Selenium commands vs using pollUntil which executes code in the remote browser.
I'm checking to see if the user ended up at a protected URL after logging in here. Is there a better way to check this besides polling?
Best practices: do I need to make an assertion with Chai or is it even possible when I'm polling and waiting for stuff as my test? For example, in this case, I'm just trying to poll to make sure we ended up at the right URL within 30 seconds and I don't have an explicit assertion. I'm just assuming the test will fail, but it won't say why. If the best practice is to make an assertion here, how would I do it here or any time I'm using wait?
Here's an example of my code:
'create new account': function() {
return this.remote
// Hidden: populate all account details
.findByClassName('nextButton')
.click()
.end()
.then(pollUntil('return location.pathname === "/protected-page" ? true : null', [], 30000));
}
The pollUntil helper works by running an asynchronous script in the browser to check a condition, so it's not going to work across page loads (because the script disappears when a page loads). One way to poll the current remote URL would be to write a poller that would run as part of your functional test, something like (untested):
function pollUrl(remote, targetUrl, timeout) {
return function () {
var dfd = new Deferred();
var endTime = Number(new Date()) + timeout;
(function poll() {
remote.getCurrentUrl().then(function (url) {
if (url === targetUrl) {
dfd.resolve();
}
else if (Number(new Date()) < endTime) {
setTimeout(poll, 500);
}
else {
var error = new Error('timed out; final url is ' + url);
dfd.reject(error);
}
});
})();
return dfd.promise;
}
}
You could call it as:
.then(pollUrl(this.remote, '/protected-page', 30000))
When you're using something like pollUntil, there's no need (or place) to make an assertion. However, with your own polling function you could have it reject its promise with an informative error.

MVC Grid Delete Record Action Performing Full Page Load, How to stop this?

I have an mvc grid.
Next to each record is a delete button.
This delete button corresponds to an action DeleteRecord. The action deletes this record and performs a RedirectToAction("MyGrid");.
This works pretty well but what is annoying is the fact that my redirectaction causes the entire page to reload. This is something I am trying to stay away from, but can't seem to figure out a way around this.
I start out like this.
/MyApp/MyGrid => click delete
/MyApp/DeleteRecord => redirect
/MyApp/MyGrid => full reload of page
Maybe this isn't possible but I tried doing this by using overriden actions and actions with different action names, but this didn't solve my full reload. I am new to MVC so maybe this isn't even possible. I was thinking maybe if I just did an ajax.post on the clientside that I could get away from this but the more I think about it the more likely that it just will end up in the same action performing the same redirect.
Any ideas on how to get around this situation?
I actually ended up just tying into the callback function of the grid and the inline delete of the grid function and it worked. Although, extremely hackish, it stops the full post back by hoping into the inline grid delete code. Although, you can't count on the callback javascript routines to run in order as that is just how javascript works right. ; o
s.SettingsEditing.DeleteRowRouteValues = new { Controller = "Home", Action = "DeleteRecordGrid" };
s.ClientSideEvents.EndCallback = "function(s,e) { OnEndCallback(s, e, 'delete') }";
<script type="text/javascript">
function deleteWithoutPostback(eVisibleIndex) {
var okToDelete = confirm("Do you really want to delete this record?");
if (okToDelete == true) {
myGrid.DeleteRow(eVisibleIndex);
myGrid.ClearFilter();
} else {
return;
}
}
function OnEndCallback(s, e, callType) {
if (typeof callType == 'undefined') {
if (callType == 'delete') {
myGrid.Refresh();
}
}
}
</script>

dojo - programmatic way to show invalid message

dojo newbie - giving it a shot.
After submitting a form, If an error is returned from the server I would like to show that message on the dijit.form.ValidationTextBox
var user_email = dijit.byId("login_user_email");
user_email.set("invalidMessage", data["result"]["user_email"]);
//need to force show the tooltip but how???
Any help much appreciated.
See it in action at jsFiddle.
Just show tooltip:
var textBox = bijit.byId("validationTextBox");
dijit.showTooltip(
textBox.get("invalidMessage"),
textBox.domNode,
textBox.get("tooltipPosition"),
!textBox.isLeftToRight()
);
Temporarily switch textBox validator, force validation, restore the original validator:
var originalValidator = textBox.validator;
textBox.validator = function() {return false;}
textBox.validate();
textBox.validator = originalValidator;
Or do both at once.
I think you can show the tooltip via myVTB.displayMessage('this is coming from back end validation'); method
you need to do the validation in the validator-method. like here http://docs.dojocampus.org/dijit/form/ValidationTextBox-tricks
you also need to focus the widget to show up the message! dijit.byId("whatever").focus()
#arber solution is the best when using the new dojo. Just remember to set the focus to the TextBox before calling the "displayMessage" method.
I am using dojo 1.10 which works create as follows:
function showCustomMessage(textBox, message){
textBox.focus();
textBox.set("state", "Error");
textBox.displayMessage(message);
}
Dojo reference guid for ValidationTextBox: https://dojotoolkit.org/reference-guide/1.10/dijit/form/ValidationTextBox.html
I know this question is ancient, but hopefully this'll help someone. Yes, you should use validators, but if you have a reason not to, this will display the message and invalidate the field:
function(textbox, state /*"Error", "Incomplete", ""*/, message) {
textbox.focus();
textbox.set("state", state);
textbox.set("message", message);
}
You can call directly the "private" function:
textBox._set('state', 'Error');
You get the same result as #phusick suggested but with less code and arguably in a more direct and clean way.
Notes:
_set is available to ValidationTextBox as declared on its base class dijit/_WidgetBase.
Live demo:
http://jsfiddle.net/gibbok/kas7aopq/
dojo.require("dijit.form.Button");
dojo.require("dijit.form.ValidationTextBox");
dojo.require("dijit.Tooltip");
dojo.ready(function() {
var textBox = dijit.byId("validationTextBox");
dojo.connect(dijit.byId("tooltipBtn"), "onClick", function() {
dijit.showTooltip(
textBox.get('invalidMessage'),
textBox.domNode,
textBox.get('tooltipPosition'), !textBox.isLeftToRight()
);
});
dojo.connect(dijit.byId("validatorBtn"), "onClick", function() {
// call the internal function which set the widget as in error state
textBox._set('state', 'Error');
/*
code not necessary
var originalValidator = textBox.validator;
textBox.validator = function() {return false;}
textBox.validate();
textBox.validator = originalValidator;
*/
});
});