Check if page gets refresh or closed in Javascript - javascript

I want to detect whether page is refresh or closed.On close, I am clearing session. But my session getting clear on browser refresh also. I have searched but not found any solution.
I have used various method to solve:-
Method 1(this work but session out on refresh also.)
function HandleOnClose(event) /*called on onbeforeunload on body*/ {
if (event.clientY < 0) {
var request = GetRequest();
Urladd = "logout url goes here" //logiut URL work fine
request.open("POST", Urladd, false);
request.send();
}
}
function GetRequest() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
Method 2:
How to know whether refresh button or browser back button is clicked in firefox
Method 3:Identifying Between Refresh And Close Browser Actions

Related

Opening multiple sites on the browser tabs with window.open

I have the following code and need to open two new tabs pointing to 2 web sites. For example: www.google.com and www.yahoo.com
It works only if I put one site in there
window.open("https://www.google.com");
but not when both lines
window.open("https://www.google.com");
window.open("https://www.yahoo.com");
Can you tell me what i need to do to be able to open both sites?
(function() {
document.getElementById("btnAsync").addEventListener('click', makeRequest);
function makeRequest() {
var httpRequest = new XMLHttpRequest(); // Initiatlization of XMLHttpRequest
if (!httpRequest) {
alert(' Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
alert(httpRequest.responseText);
} else {
alert('There was a problem with the request.');
}
}
};
window.open("https://www.google.com");
window.open("https://www.yahoo.com");
}
})();
<button id="btnAsync" type="button">Click Me</button>
I run your code. Both sites opened. But before it opens browser blocked popup window so i had to allow it to open. Try your code. And dont forget to allow popup after pressing button.
In the bad old days, it was common for malicious websites to fork bomb browsers by triggering an infinite loop of new windows.
They implemented protection against this by allowing new windows (and tabs) to be opened only when the function was triggered by a user event (e.g. a click but not a page load) and restricting this to opening a single window.
Some browsers may prompt the user to allow an additional window to open, but there is no way for a website to simply bypass this important security feature.

Check if still connected to host with Javascript

In some place there is a policy which needs user to click button Continue to enter for example music streaming website.
Let's assume I want to use this website for a time longer than this policy accepts. After some period of time the music stops playing and after refreshing webpage - policy asks you for clicking Continue again, even if you have not left the page.
I'd like to make a script which would check if a connection still persists, but without website refreshing (because it plays music).
I've already created script which would click Continue, but don't know how to (and if it is possible) check connection, if connection is broken then refresh website and click Continue.
Can it be done with GreaseMonkey?
I enter http://deezer.com/
Script click Continue for me
I listen to music
Script is checking connection
if connection is ok go to 3.
Refresh website
Go to 2.
Click script:
if (document.title == 'Click continue')
{
var a = document.getElementById('continue-text');
a.children[1].click();
}
If no policy then the return of page is:
200 OK 318ms
If policy goes on, then it returns:
200 Forbidden 91ms
You can check the connection like this:
function checkConnection() {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if(xmlhttp.status == 200){
// this might need some customisation:
var connected = document.getElementById("id_of_the_continue_button") ? true : false;
if (!connected) {
reconnect();
}
}
else {
reconnect();
}
}
}
// here you'll need a relevant url:
xmlhttp.open("GET", "http://deezer.com/", true);
xmlhttp.send();
}

php not returning any result to javascript ajax object

I'm trying to use ajax, I've used it before, copied the code from my previous html file and altered the values sent, php file to process the code and I'm using the POST method. However, the php script does not return anything to the html page. I've checked all i can, so I'm here now.
function look () {
var x = document.getElementsByTagName('option')[document.getElementById("region").selectedIndex].value;
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data
// sent from the server and will update
// modal section in the same page.
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById("accordion");
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
// Now get the value from user and pass it to
// server script.
ajaxRequest.open("POST", "search.php", true);
ajaxRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");
alert(x);
ajaxRequest.send("region=" + x);
}
The php code is a simple
<?php
echo "The world is blue.";
?>
yet, it returns nothing to the chosen div.
You've probably not posted enough information for us to answer your question. But, I acknowledge that you probably are not sure what questions you need to ask in the first place.
First, I must agree with #cgf. jQuery or the alike will make this easier.
But lets focus on the problem at hand. We need to know what is happening behind the scenes.
The best way to do this is through a developer tool bar such as firebug. Chrome has one built in.
So, load up chrome and hit F12. This should bring up a very busy looking pane on the bottom of your window. Select the Network tab and then request your page / trigger your javascript. What output do you get in the network tab? Mainly, under status do you get 200, 500 (server error) or perhaps 404 (not found)? Update your question above with what you see / get.
My hope is that this should point you in the right direction.

Call to xmlhttprequest from page onload event is not working OK when Back from another page

After going from my page to anther page by pressing a link, and than back to current page, than in call to xmlhttprequest from onload event, The js code of xhr.open and xhr.send is working, but the sever side code called by xhr is not running, and in xhr.onreadystatechange function the xhr.responseText is returning his old value.
In this scenario off comming back from another page, call to xmlhttprequest from document.onreadystatechange event is also not working OK.
The same code works OK when I call it from onload in the first page loading (before going to another page and returning), or when I call it from a button click.
Why the call to xmlhttprequest from onload event is not working OK when Back from another page?
I'm using Chrome.
Here is my code:
<script type="text/javascript">
function CallAJAX() {
xhr = null;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = AJAX_onreadystatechange;
xhr.open("GET", '/MyPage.aspx', true);
xhr.send(null);
}
function AJAX_onreadystatechange() {
if (xhr.readyState == 4 && xhr.status == 200) {
alert('xhr.responseText=' + xhr.responseText);
}
}
window.onload = function () {
//alert is working also after going to link and than back to current page
alert('alert')
//Call to xmlhttprequest from page onload event - is Not working OK - after going to link and than back to current page
CallAJAX();
}
</script>
<!--here is the "link" mentioned in the above comment-->
link
<!--Call to xmlhttprequest from button onclick event - is working OK-->
<input id="Button1" type="button" value="button" onclick="CallAJAX();" />
Update
I found the problem:
In some browsers, and in some circumstances, xhr brought the xhr.responseText
value from browser cache, instead to call server.
Here is the solution:
This problem solved by adding unique query string param to url param of xhr.open. This guaranty that the ajax will avoid using the cache, and always hit the server, because with the unique param, the url is turned to unique in every call to xhr.open.
The unique value is produced by "new Date().getTime()" which returns the number of milliseconds between midnight of January 1, 1970 and now.
This is the solution code:
xhr.open("GET", '/MyPage.aspx?uniqueParamVal=' + new Date().getTime(), true);

Stop page refresh

I'm writing a small piece of code which takes input from a user via html form to then retrieve information (in xml) from a server (which is running locally) using XMLHttpRequest, once I get the information I output it into a list using the method I've written for the onreadystatechange. However once it's written the list to the page it automatically refreshes the page and the list disappears. I'm absolutely lost as to why it is doing this?! I've managed to forcefully stop the page refreshing using window.onbeforeunload and stopping the refresh, but I can't help but think there is a better way around this and that I must be doing something wrong. My code is as follows:
var xmlhttp=null;
function byObserver(){
var a = document.forms["byObserverForm"]["observerName"].value;
a = encodeURIComponent(a);
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp) {
xmlhttp.onreadystatechange = onReadyStateByObserver;
xmlhttp.open("GET","http://localhost:8004/birdobs/observer/" + a, false);
xmlhttp.send();
}
return false;
}
function onReadyStateByObserver(){
if (xmlhttp.readyState == 4){
if (xmlhttp.status == 200){
var xmlDoc = xmlhttp.responseXML;
var observations = xmlDoc.getElementsByTagName("observation");
if (observations.length != 0){
// output into unordered list
var f = document.createDocumentFragment();
var e = document.createElement("ul");
f.appendChild(e);
var ul = f.firstChild;
for (i = 0; i<observations.length; i++) {
var li = document.createElement("li");
var te = document.createTextNode(observations[i].getAttribute("observer"));
li.appendChild(te);
ul.appendChild(li);
} // end for
document.getElementById("content").appendChild(f);
window.onbeforeunload = function(){
return "Refresh";
}
}
}
}
//have also tried return false here
}
Any help would be highly appreciated as I've spent so long trying to fix this, many thanks in advance! (I haven't included the HTML as I thought it wasn't needed, but please ask if it would help and I'll post it up!) I'll just finally add I'm running this in chrome.
This is most likely because the browser is still submitting the form. You need to inform the browser that you do not wish for the default form submit handling to happen.
Returning false from your onsubmit method should do this.
** Update **
Presuming you are using the onsubmit handler and the function being called is byObserver then try the following:
<!-- HTML -->
<form ... onsubmit="return byObserver()">
// javascript
function byObserver() {
...
return false;
}
you should stop the default event when you submit the form, e.g. with return false at the end of the function called on submit. Maybe the page is refreshing because you're not stopping the submit event (and the browser is thus redirected to the page specified on action attribute of your form)
At the end of the method that's invoked by submitting your form you need to return false;
It looks like the function being fired is byObserver and so you'd do the following:
function byObserver(){
[...]
return false;
}

Categories

Resources