Clear session on window close - javascript

I am working on a examination project, When user starts a test it open in new window by window.open(). If user close a test before it finish then session creates a problem so I want to clear session when user close the browser window or hide/disable close button before test completes.

nothing you come up with here will not be overrulable by the user; welcome to client-side programming (the actual browser "close" button is not within your reach). You can tap into onclose (lots of sites do this in order to pop up a confirm("do you want to leave this page?") dialog) but even that is very easy to bypass by anyone who knows how to open a browser console (F12 on every browser, for example) because they can just redefine window.confirm = (() => true); and not get bothered by confirm dialogs.

Partial solution would be to use the onbeforeunload and send a request back to the server once it is invoked.
Once the request is received on the server, you can destroy the session.
Again, this is easy to bypass on the client side but does provide extra functionality.
window.onbeforeunload = function() {
// AJAX to server
};

You could use this answer here:https://stackoverflow.com/a/1119324/1489237
That would give you that message "are you sure you want to leave this page?"
On that function,instead of a message you can submit an ajax that will call a script to do a session_destroy() before closing the page.

I think you can set session expiration time to be few seconds? and perform ajax requests to maintain it, while student is answering questons

Can you use popup block with iframe inside?
<div id="test-popup">
<iframe src="/test/12345">
</div>
And open it with JS:
$('#test-popup').show();
This is for example only. You need more CSS and JS to make it works.

Related

call different function during page refresh and close javascript

I am creating a web app using web socket, which on user closes the tab I will make an API call to the server to clean the user related info in the server, I used onBeforeUnload listener in javascript, but this method also gets triggered during the page refresh.
I need to trigger a method only during the tab or browser close, but not during the page refresh.
I know this question has been asked several times, some solution suggested using cookies will not be helpful in my case
navigator.sendBeacon() method can be used for sending data from browser to server when a tab is closed.
Here is an example:
window.addEventListener("unload", function informServer() {
navigator.sendBeacon("/server-api-to-collect-data", my-data)
})
More information:
https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon
As far as I know, you can not listen to actions of browser's tab close or exits. For your application it is an "unload", whatever caused it...
The only thing I could think about is maybe add a listener for keyboard key press (F5), however it doesn't help in case someone refreshed by clicking on the browser's refresh button.
I don't know what is the use case, but most of the things should be done when a page unloads (no matter why) and/or when the page is back up again. So most of the solutions are for situations where your page is loaded again - and then you can determine what was the source of the load and make farther actions, but since you have an option were someone can close and never come back, that might not be the case.
Some solutions for page load up:
You can use Navigation type.
You can check referer.
You can use cookies or other types of browser storage.
I would recommend to rethink about your use case. Maybe you can do whatever you want on load up or leave it on onBeforeUnLoad without knowing the future :)

Popup window when the page is closed

hello i have a Django base app and one of its apps is chatting with customer service.
i want when the customer clicks on the the [x] icon or close the window, a small popup window should come up that include:
1.a string like "thank you, and we hope you can take time and answer the survey:"
2. a button that directs the customer to the survey page.
i have this part of the chatting app java script file:
window.onbeforeunload = function() {
window.open ("http://gadgetron.store/male_chatbot/popup/"); <= i have tried it and it doesn't work
$.ajax({
type: 'GET',
url: 'http://gadgetron.store/chatbot/run_python_clear_chatM/',});}
thank you,
I tried some thing like that before, but I think the browser disabled the popup customization. and note that you need configure the ajax call as synchronous (check this). you can use window.onunload event handler, and then small popup with confirm and cancel button, if you click on confirm you script will be executed and the tab will closed
For user experience reasons, browsers do not allow opening Popups during the unload-phase, which this event is part of. The only thing you can do is open a popup, asking the user to confirm that he really wants to leave the page. This is achieved by returning any non-empty string from the event callback (ie. return "Are you sure you want to leave?"; where you currently call window.open). The text inside this confirmation window can no longer be influenced by the application for most modern browsers.
For information regarding popups during the unload phase, have a look at the WHATWG Spec, most importantly the ignore-opens-during-unload counter which blocks document.open when set to any value greater than 0.

Differentiate browser refresh and browser close

I want to set a cookie when a visitor on the page closes the browser.
I used onbeforeunload method like this
<script language="JavaScript" type="text/javascript">
window.onbeforeunload = confirmExit;
function confirmExit()
{
return "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?";
}
</script>
followed this link
But found out that even refresh of page or click on any hyper link on the page,pops up an alert.
I need to set cookie only when visitor clicks cross button of browser and not on page refresh.
I followed some of the links like the one above and another here. And found from the post that we can not differentiate between close and refresh. But those posts were 3-4 years back.
Is there is any way to differentiate these events using JavaScript or Jquery?
I'm afraid you have no way to tell.
The only thing you can do is overload clicks on links and set a flag. But you can never know if it is a refresh or a close...
Hmm, what about this:
Set a cookie onbeforeunload
Globally onload, check the timestamp of the cookie to see whether this was a link, or a new session
If the timestamp difference is only a few seconds, delete the cookie
Well, unload is called when browser is closed and onload is called when you try to reload. You can use these properties and set flags , and fire events accordingly
Browser close and reload Check this link for more details

Cross Domain Pop Ups

My flow is as follows: the user clicks sign in on site 1. a pop up is opened from site 2 asking him to login using twitter. he then logs in - using oAuth, so the page changes. After a successful login the pop up should close and the code on site 1 should receive a notification.
What didn't work:
WebIntents - well, the examples on their site didn't even work, so I didn't try it locally..
easyXDM - communicates with an iframe, not a popup.
porthole - same, uses an iframe.
A horrible solution is refreshing the iframe every couple of seconds, to check if the user logged in already.
Is there a better way to do this? better libraries?
if you can refer the popup to another page after the user is logged in, you could use this:
main page:
localStorage.setItem('user_signed_in', false); // signed out by default
window.open("http://www.google.com/", "google_window", "menubar=no,resizable=no,scrollbars=no,status=no,width=400,height=300");
(function look_up() {
if(localStorage.getItem('user_signed_in')) {
go_on();
} else {
setTimeout(look_up, 500)
}
}());
function go_on() {
...
}
refer page:
localStorage.setItem('user_signed_in', true);
window.close();
Keep in mind that the refer page has to be on the same domain as your main page.
And, don't be afraid of bad support for localstorage in other browsers,
but if you really want to support oldies, you can use cookies, I believe.
When a user clicks a sign in button on site1 a pop up is opened from site2.
I'm assuming your using window.open thru an iframe to do this, and that you have already figured out how to bypass most browsers spam blockers etc.
Since you are opening this pop up as a new window, you are now in control of that window, and you can actually send stuff back from the new window.
This will be somewhat pseudo code, but just to make an example!
Lets say a user signs in with a link looking something like this:
<a href="" onclick="window.popup=window.open('/twitter/login.php', 'Twitter login', 'width=450,height=500'"</a>
Your pop up can now be refferenced by window.popup, and inside window.popup the original page is now called the window.opener.
On the same site that opens the popup you have a function, like this:
document.handleLogin = function (returnedDataFromPopup) {
console.log(returnedDataFromPopup);
}
After the user has logged in with oAuth, you need to redirect to a new page, this is explained in both the oAuth and Twitter guides, and you need to make that redirect happen inside the popup, and then capture the information from the login on that page and send it back to the original document and the handleLogin function.
Depending on what your using, in most PHP implentations you do something like this to get the data from the login, and this is of course after doing all the token and consumer key stuff:
$userinfo = $oAuth->getAttributes(); //or something similar, depends
So when redirecting from Twitter to a new page, the new page would look something like:
<? php
$userinfo = $oAuth->getAttributes();
?>
<script type="text/javascript">
window.opener.document.handleLogin(<?php echo json_encode($userinfo) ?>);
window.close();
</script>
This will actually run the handleLogin() function on the page that opened the popup, and it will send the userinfo from the popup to that function on the original page and then close the popup window.
I've used this technique with oAuth, OpenID, Google etc. and it works just fine without any need for local storage, cookies or page refresh at all, since you are in control of the popup window you can send information back and forth and you could even change the adress of the popup from the opening document on the fly if you wanted by doing something like this:
window.popup.location.href = 'google.com';
This is handy in some cases, for instance OpenID will by default close the popup and redirect the document.opener to the page specified, this is not what you want, and to overcome this you would have to open the popup on some random page, preferably an empty page that you control, and then redirect the popup's href to Twitter immediately after the popup is opened.
It all looks very complicated, but it is doable, and if you get this far, you now have the data, an all you have to do is somehow push it to site1 thru the iframe that holds site2. As pushing is'nt really possible without websockets or some sort of event driven server, like node.js, you will probably have to rely on long polling or something else, there are many ways to do this, and I'm sure you'll figure it out, but if you have some control over scripts running on site1, and you obviously have control over site2, then you can actually access some data thru an iframe with a little javascript, but I've never actually done that so I do not know exactly how it works.
It's not really relevant, but I don't really see why it would be useful for someone to login thru your site with an iframe from some other site, and it all seems strange to me, but thats up to you to figure out.

want to detect browser close event?

I am working on any application in which i need to detect that whether user close the tab or browser so I can disconnect the user from other user basically its an chat application.
I have used :-
window.onbeforeunload = confirmExit;
function confirmExit() {
if(needToConfirm) {
return "Leaving this page will end your conversation.";
}
Its work fine, when I try to close the browser or tab it shows an popup with message "Press OK to continue, or Cancel to stay on the current page."
I want to perform task when user click on Ok button and if he press cancel then will stay on current page.
Please Help me :(
Thanks in advance
Ansh J
This is not possible.
You could handle the unload event and send an AJAX request there, but that might not be completely reliable.
The best solution is to send an AJAX hearbeat every x minutes, and consider the user disconnected if you stop receiving the heartbeat.
Go the other way around: when you receive the Unload event, send the server a message that informs the user is about to disconnect. The server waits for some time and then automatically disconnects.
Then, if the user click cancel and stays on the page, you send a message to the server to inform that the client is still alive.
The downside is that, if the user waits too long to click cancel, he might be disconnected.
Why not have the client's periodically 'ping' the server to let it know that they are still there, and if a user misses say 3 pings then it will be marked as logged off?

Categories

Resources