logout when window closed using javascript - javascript

I have used window.onbeforeunload on my javascript codes, but apparently it only works for FireFox:
<script type="text/javascript">
window.onbeforeunload = function (e) {
location.href="admin.jsp?action=logout";
};
</script>
I need this to close at least 5 renowned browsers (firefox,IE,opera,safari,and chrome). Can anyone help me out?

Use a synchronous XHR to do this, and use the unload event instead of onbeforeunload:
window.addEventListener('unload', function() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'admin.jsp?action=logout', false);
xhr.send(null);
}, false);

Related

run a function before Firefox close the window

This is my first topic here! So, I'm trying run an ajax function before the Firefox's window close, my code works when I close the tab, but window not. How can I do this?
Detail: Only Firefox don't run the function when window is closed and if possible without use JQuery.
window.onload = function(){
window.addEventListener('beforeunload',function(event){
var ajax = new XMLHttpRequest();
ajax.open("POST","index.php",true);
ajax.send();
}, false);
}
Try navigator.sendBeacon
var some_ajax_data;
window.onbeforeunload = function() {
navigator.sendBeacon('/data.php', some_ajax_data);
};

Javascript AJAX Upload incompatible with Firefox

I use AJAX upload for my site, and Javascript is the choice (not jQuery).
But What I have come up with does not work with Firefox. Here is the XMLHttpRequest code block:
var xhr = new XMLHttpRequest();
xhr.open("POST", "upload.php");
xhr.onprogress = function(event){
if(event.lengthComputable)
{
console.log(event.loaded);
}
};
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.send(formData);
And pay attention to xhr.onprogress event.
Alternatively, I also use the following code for progress:
xhr.upload.addEventListener("progress", function(){
// do something
}, false);
But:
For the first solution which is xhr.onprogress it has a problem:
It just shows the amount of event.loaded after the upload has been finished. This amount is the same as the file size since the upload has fully loaded the file.
It works in both FF and chrome, but I don;t want it to just throw a value after the progress has reached to its end.
The second solution, though, is nice and works OK, but it in no way works in firefox. In firefox however, no error is thrown, and as I have tested, the progressEvent does not get triggered at all.
Both chrome and Firefox are of latest versions.
I think problem is you add onprogress listener after open(), it should be done before:
var xhr = new XMLHttpRequest();
xhr.onprogress = function (event) {
if (event.lengthComputable) {
console.log(event.loaded);
}
};
xhr.open("POST", "upload.php");
Or:
var xhr = new XMLHttpRequest();
xhr.addEventListener("progress", function (event) {
if (event.lengthComputable) {
console.log(event.loaded);
}
}, false);
xhr.open("POST", "upload.php");

XMLHttpRequest from Firefox Extension

I'm using XMLHttpRequest to exchange data between server and Firefox extension I'm developing. Unfortunately, those requests seem somehow connected with the currently open page - if I try to issue request while the current tab is closing, it will fail with an error. How can I make my requests originate from the extension itself, independently of what's going on in tabs?
EDIT: Here is the code that reproduces this problem. It's run as the main extension body (I based my design on the "Hello world" tutorial from http://kb.mozillazine.org/Getting_started_with_extension_development, so no Add-on SDK). This means that it's executed in the same place as the code from "overlay.js" in above tutorial.
function createXMLHttpRequest() {
return Components.classes["#mozilla.org/xmlextras/xmlhttprequest;1"]
.createInstance(Components.interfaces.nsIXMLHttpRequest);
}
function issueRequest() {
var req = createXMLHttpRequest();
req.open("GET", "http://google.com", true);
req.addEventListener("load", function(event) {
alert("SUCCES");
});
req.addEventListener("error", function(event) {
alert("ERROR");
});
req.send();
};
window.addEventListener("DOMContentLoaded", function(event) {
issueRequest();
var doc = event.originalTarget;
var win = doc.defaultView;
win.addEventListener("unload", function(event) {
issueRequest();
});
});
This results in "SUCCESS" after opening of new tab, and "ERROR" after closing it. I would prefer to have two SUCCESSES.
If that script is running in a browser window overlay then you attached your DOMContentLoaded handler to the wrong node - you will only get notified when the browser window itself loads. Consequently, your unload handler waits for the browser window to the closed, you probably intended to wait for a tab to be closed. The correct code would look like this:
// Wait for the browser window to load before doing anything
window.addEventListener("load", function() {
// Attach a listener to the tabbrowser to get notified about new pages
window.gBrowser.addEventListener("DOMContentLoaded", function(event) {
issueRequest();
var doc = event.originalTarget;
var win = doc.defaultView;
win.addEventListener("unload", function(event) {
issueRequest();
});
}, false);
}, false)

Opera + XMLHttpRequest

I`m from Russia, so sorry for my bad English.
I want to load the main page of my site by js, and i use this script:
<script type="text/javascript">
function httpGet(theUrl) {
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false );
xmlHttp.send(null);
return xmlHttp.responseText;
}
alert(httpGet('http://site.ru'));
</script>
Script located at site.ru/page123.
It works in Firefox and really alert my main page, but if i run it in Opera, nothing happens. Please, fix my code, i can`t see any error in it. Thanks in advance.
XHR is usually asynchronous (switching it to synchronous mode is not recommended for reasons like freezing the browser). You better use a callback.
Since dealing with XHR manually is annoying, I'd suggest you to use jQuery. Using jQuery your code would look like this (that's just the easiest/most simple way to do it):
$.get('http://site.ru', function(resp) {
alert(resp);
});

Running Ajax in IE, FF, and Safari

I'm trying to create an ajax connection to a weather xml feed and then parse returned data. I don't have any issues making a connection via IE, but for some reason I don't have any luck in FF or Safari. Basically what I'm doing is running an html file that contains the following code.
<html>
<script type="text/javascript" language="javascript">
function makeRequest(zip) {
var url = 'http://rdona.accu-weather.com/widget/rdona/weather-data.asp?location=' + zip;
//var httpRequest;
var httpRequest = false;
if (window.XMLHttpRequest) {
document.write("xmlhttprequest");
httpRequest = new XMLHttpRequest();
if (httpRequest.overrideMimeType) {
httpRequest.overrideMimeType('text/xml');
// See note below about this line
}
}
else if (window.ActiveXObject) { // IE
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = function() { alertContents(httpRequest); };
httpRequest.open('GET', url, true);
httpRequest.send('');
}
function alertContents(httpRequest) {
if (httpRequest.readyState == 4) {
if (httpRequest.status == 200) {
alert(httpRequest.responseText);
} else {
alert('There was a problem with the request.');
}
}
}
makeRequest(84405);
</script>
</html>
Any help and or suggestions would be greatly appreciated.
I'm afraid you will run into some issues because of same origin policy, meaning that you cant do XMLHTTPRequests to another domain.
Not even jQuery (which you really should check out anyways) can help you with that.
I strongly suggest you use a framework to do this sort of thing. Frameworks will do all of the browser compatibility stuff for you.
On the other hand, if you are interested in how to do this as an academic exercise... still get a framework! See how the framework does it and you will immediately learn all of the pitfalls.
Mootools is my framework of choice.
In order to perform a basic AJAX request in Mootools you would do the following:
window.addEvent('domReady', function() {
new Request({
'url': "The url where you want to send the request
'data': "Some data to send. It can be an object."
}).send();
});
Full documentation for the Request class can be found here.
If you want to see how Mootools implements cross-browser AJAX, you can find the source of the Request class here.
You'll find the source for Browser.Request particularly useful.
For cross browser stuff, I recommend you use a library like JQuery because it will quietly smooth over IE vs Firefox vs Safari etc issues. Also to make the code format properly, use the 101010 button in the toolbar.

Categories

Resources