Firefox WebExtension : check if extension already exists - javascript

I'm porting my Chrome extension to a Firefox WebExtension, so far so good, I manage to communicate smoothly with my content, background scripts and my executable.
I would like now to check the existence of my extension. This is actually the way I do it :
Browser script
// browser-script.js
var isExtensionHere = false;
$("#is-extension-here").click(function(){
console.log("Check the existence of the extension");
window.postMessage({
direction: "from-page-script",
message: "areYouThere"
}, "*");
});
window.addEventListener("message", function(event) {
if (event.source == window &&
event.data.direction &&
event.data.direction == "from-content-script") {
if(event.data.message == "OK") {
isExtensionHere = true;
}
}
});
Content Script
// content-script.js
window.addEventListener("message", function(event) {
if (event.source == window &&
event.data.direction &&
event.data.direction == "from-page-script") {
if(event.data.message == "areYouThere") {
window.postMessage({
direction: "from-content-script",
message: "OK"
}, "*");
}
}
});
It works fine when the extension is here. But when it is not, obviously I don't get an answer from my extension. How can I know then how to trigger a popup or a message when the extension is not here ?

You can reverse the logic: make the page listen for a ping from the extension. You need to be mindful of when scripts execute (e.g. depending on run_at parameter) in relation to each other, so that you don't accidentally send a message before the page starts listening.
You can use another method of announcing presence to the page: a content script can add an invisible DOM element with a known ID, and you can check for its presence from the page.
If you want to keep the current approach, you can set a timer for the response to happen. Something like, say, 200ms should be more than enough.
You can implement this as a Promise, since it can only be resolved once:
var isExtensionHere = new Promise((resolve, reject) => {
const listener = (event) => {
if (
event.source == window && event.data.direction
&& event.data.direction == "from-content-script"
&& event.data.message == "OK"
) {
resolve(true);
}
}
setTimeout(() => {
window.removeEventListener("message", listener);
resolve(false); // Will have no effect if already called with true
}, 200);
window.addEventListener("message", listener);
window.postMessage({
direction: "from-page-script",
message: "areYouThere"
}, "*");
});
// Sometime later
isExtensionHere.then((result) => { /* ... */ });
If you want to dynamically re-check, make isExtensionHere a function that returns a new Promise every time.

Related

Chrome Extension And Dom Capture

I created a chrome extension for one of my pages. I'm getting the data in a dom element on the page and querying the api and calling it back. On the site where I get data, the page does not reload when switching between pages. So I can't catch Dom loading or locationchange in foreground.js because the page is not refreshed and i solve my problem by timeout.The dom in foreground.js is only triggered when the page is refreshed. The codes I wrote in settimeout are triggered when switching between pages. How can i solve this problem without timeout?
background.js CODES
chrome.tabs.onUpdated.addListener((tabId, changeInfo,tab) => {
if(changeInfo.status == "complete" && tab.status == "complete") {
chrome.scripting.executeScript({
target: {tabId: tabId},
files: ["./foreground.js"]
})
}
});
foreground.js CODES
document.addEventListener("DOMContentLoaded", () => { alert('Dom'); }); //not working
window.addEventListener('locationchange', function(){
console.log('location changed!');
}) //not working
setTimeout(() => {
let find = document.querySelector(".contentsdetailscontainer").textContent;
},1000); //this is working
foreground.js executed when document.readyState is complete, which means DOMContentLoaded has already been fired.
If at that point the needed element is not present in the DOM, you can use the Mutation Observer and wait for it.
Here is a simple example (very inefficient because it observes entire body, if only a specific element changes, you should observe it instead, so use it only as a guide):
var nodeFound = false;
const observer = new MutationObserver(() =>
{
const node = document.querySelector(".contentsdetailscontainer");
if (node && node.textContent)
{
if (!nodeFound)
{
//only show alert once per new page.
alert("node found");
nodeFound = true;
}
}
else
{
nodeFound = false; //reset in case page updated again
}
});
observer.observe(document.body, {subtree: true, childList: true});

Edge extension: runtime.sendMessage doesn't receive response

I'm writing an Edge extension and struggling with communication between content script and background script.
I'm sending a message from content script to background one:
browser.runtime.sendMessage({ name: "get_card_for_website", url: document.URL }, function(response) {
console.log("Got card for the website:");
console.log(response);
if (response != undefined) {
if (response.card) {
g_card = response.card;
callback(response.card);
}
}
});
Listener in background script is implemented like this:
browser.runtime.onMessage.addListener(function (request, sender, sendResponse) {
if (request.name == 'get_card_for_website') {
get_card_for_website(request.url)
.done(function(element) {
if (element.cards && element.cards.length != 0) {
if (element.cards.length == 1) {
sendResponse({'card': element.cards[0]});
}
else {
get_one_card_for_site(element);
sendResponse({'card': ""});
}
}
});
}
}
Debugger shows message is sent to background script and corresponding code is executed up to sendResponse. But back in content script this callback function is never executed. Console shows no errors.
What could I miss?
Update: I've found out that some tabs receive responses and some don't. I don't really understand difference between first and second ones.
Ok, I figured out the reason of the problem. sendResponse() was called in .done() function, which is called asynchronously. And according to manual:
The sendResponse callback is only valid if used synchronously, or if
the event handler returns true to indicate that it will respond
asynchronously.
So I've modified my background script's function this way:
if (request.name == 'get_card_for_website') {
get_card_for_website(request.url)
.done(function(element) {
if (element.cards && element.cards.length != 0) {
if (element.cards.length == 1) {
sendResponse({'card': element.cards[0]});
}
else {
get_one_card_for_site(element);
sendResponse({'card': ""});
}
}
});
return true; // <----- this part I've added
}
And now it's working like a charm.

NW.js open a new window and close it on event

I'm migrating my NW.js v0.12.3 to the new NW.js v0.17.3.
In my old app, I used to open a window to show an incoming call notification. And if the user answered the call or hangs up I closed the window based in a special event listener.
This is my code which works with no problems in v0.12.3:
var notificationWin;
window.onload = function () {
var messageHandler = function(event) {
if(event.data.key == 'incomingCall'){
win.requestAttention(1);
notificationWin = gui.Window.open('notification.html', {
frame: false,
toolbar: false,
focus: true,
icon: "app/imgs/traywinaz.png",
title:"Incoming Call"
});
notificationWin.on ('loaded', function(){
....
});
}else if(event.data.key == 'callRejected' || event.data.key == 'callAnswered' || event.data.key == 'callCanceled' ){
notificationWin.close();
}
}
window.addEventListener('message', messageHandler, false);
}
But in the new version I cant close the window in the call rejected or answered events. I can't get the notification window to close it.
My new code looks like this:
var messageHandler = function(event) {
if(event.data.key == 'incomingCall'){
win.requestAttention(1);
nw.Window.open('app/notification.html', {
frame: false,
focus: true,
icon: "app/imgs/traywinaz.png",
id: "callNotification"
}, function(new_notification) {
new_notification.setAlwaysOnTop(true);
new_notification.setVisibleOnAllWorkspaces(true);
new_notification.on ('loaded', function(){
....
});
});
}else if(event.data.key == 'callRejected' || event.data.key == 'callAnswered' || event.data.key == 'callCanceled' ){
try{
notificationWin = nw.Window.get('app/notification.html');
notificationWin.close();
}catch(e){
console.log(e);
}
}
};
I can only get the window inside the callback so I also tried to do something like this inside the callback:
notificationWin = new_notification;
but this closes my main window.
Any ideas of what I am doing wrong or how can I achieve this?
The documentation http://docs.nwjs.io/en/latest/References/Window/#windowgetwindow_object says Window.get([window_object]) but no idea how to get the [window_object] parameter in the new version.
Coming back to this, I resolved it by saving the reference inside de callback : "notificationWin = new_notification;" and then just calling notificationWin.close();
The first time I tried this it closed my main window but now works : )

How to check Popup blocker enabled Without loading popup window in chrome using Javascript [duplicate]

I am aware of javascript techniques to detect whether a popup is blocked in other browsers (as described in the answer to this question). Here's the basic test:
var newWin = window.open(url);
if(!newWin || newWin.closed || typeof newWin.closed=='undefined')
{
//POPUP BLOCKED
}
But this does not work in Chrome. The "POPUP BLOCKED" section is never reached when the popup is blocked.
Of course, the test is working to an extent since Chrome doesn't actually block the popup, but opens it in a tiny minimized window at the lower right corner which lists "blocked" popups.
What I would like to do is be able to tell if the popup was blocked by Chrome's popup blocker. I try to avoid browser sniffing in favor of feature detection. Is there a way to do this without browser sniffing?
Edit: I have now tried making use of newWin.outerHeight, newWin.left, and other similar properties to accomplish this. Google Chrome returns all position and height values as 0 when the popup is blocked.
Unfortunately, it also returns the same values even if the popup is actually opened for an unknown amount of time. After some magical period (a couple of seconds in my testing), the location and size information is returned as the correct values. In other words, I'm still no closer to figuring this out. Any help would be appreciated.
Well the "magical time" you speak of is probably when the popup's DOM has been loaded. Or else it might be when everything (images, outboard CSS, etc.) has been loaded. You could test this easily by adding a very large graphic to the popup (clear your cache first!). If you were using a Javascript Framework like jQuery (or something similar), you could use the ready() event (or something similar) to wait for the DOM to load before checking the window offset. The danger in this is that Safari detection works in a conflicting way: the popup's DOM will never be ready() in Safari because it'll give you a valid handle for the window you're trying to open -- whether it actually opens or not. (in fact, i believe your popup test code above won't work for safari.)
I think the best thing you can do is wrap your test in a setTimeout() and give the popup 3-5 seconds to complete loading before running the test. It's not perfect, but it should work at least 95% of the time.
Here's the code I use for cross-browser detection, without the Chrome part.
function _hasPopupBlocker(poppedWindow) {
var result = false;
try {
if (typeof poppedWindow == 'undefined') {
// Safari with popup blocker... leaves the popup window handle undefined
result = true;
}
else if (poppedWindow && poppedWindow.closed) {
// This happens if the user opens and closes the client window...
// Confusing because the handle is still available, but it's in a "closed" state.
// We're not saying that the window is not being blocked, we're just saying
// that the window has been closed before the test could be run.
result = false;
}
else if (poppedWindow && poppedWindow.test) {
// This is the actual test. The client window should be fine.
result = false;
}
else {
// Else we'll assume the window is not OK
result = true;
}
} catch (err) {
//if (console) {
// console.warn("Could not access popup window", err);
//}
}
return result;
}
What I do is run this test from the parent and wrap it in a setTimeout(), giving the child window 3-5 seconds to load. In the child window, you need to add a test function:
function test() {}
The popup blocker detector tests to see whether the "test" function exists as a member of the child window.
ADDED JUNE 15 2015:
I think the modern way to handle this would be to use window.postMessage() to have the child notify the parent that the window has been loaded. The approach is similar (child tells parent it's loaded), but the means of communication has improved. I was able to do this cross-domain from the child:
$(window).load(function() {
this.opener.postMessage({'loaded': true}, "*");
this.close();
});
The parent listens for this message using:
$(window).on('message', function(event) {
alert(event.originalEvent.data.loaded)
});
Hope this helps.
Just one improvement to InvisibleBacon's snipet (tested in IE9, Safari 5, Chrome 9 and FF 3.6):
var myPopup = window.open("popupcheck.htm", "", "directories=no,height=150,width=150,menubar=no,resizable=no,scrollbars=no,status=no,titlebar=no,top=0,location=no");
if (!myPopup)
alert("failed for most browsers");
else {
myPopup.onload = function() {
setTimeout(function() {
if (myPopup.screenX === 0) {
alert("failed for chrome");
} else {
// close the test window if popups are allowed.
myPopup.close();
}
}, 0);
};
}
The following is a jQuery solution to popup blocker checking. It has been tested in FF (v11), Safari (v6), Chrome (v23.0.127.95) & IE (v7 & v9). Update the _displayError function to handle the error message as you see fit.
var popupBlockerChecker = {
check: function(popup_window){
var _scope = this;
if (popup_window) {
if(/chrome/.test(navigator.userAgent.toLowerCase())){
setTimeout(function () {
_scope._is_popup_blocked(_scope, popup_window);
},200);
}else{
popup_window.onload = function () {
_scope._is_popup_blocked(_scope, popup_window);
};
}
}else{
_scope._displayError();
}
},
_is_popup_blocked: function(scope, popup_window){
if ((popup_window.innerHeight > 0)==false){ scope._displayError(); }
},
_displayError: function(){
alert("Popup Blocker is enabled! Please add this site to your exception list.");
}
};
Usage:
var popup = window.open("http://www.google.ca", '_blank');
popupBlockerChecker.check(popup);
Hope this helps! :)
Rich's answer isn't going to work anymore for Chrome. Looks like Chrome actually executes any Javascript in the popup window now. I ended up checking for a screenX value of 0 to check for blocked popups. I also think I found a way to guarantee that this property is final before checking. This only works for popups on your domain, but you can add an onload handler like this:
var myPopup = window.open("site-on-my-domain", "screenX=100");
if (!myPopup)
alert("failed for most browsers");
else {
myPopup.onload = function() {
setTimeout(function() {
if (myPopup.screenX === 0)
alert("failed for chrome");
}, 0);
};
}
As many have reported, the "screenX" property sometimes reports non-zero for failed popups, even after onload. I experienced this behavior as well, but if you add the check after a zero ms timeout, the screenX property always seems to output a consistent value.
Let me know if there are ways to make this script more robust. Seems to work for my purposes though.
This worked for me:
cope.PopupTest.params = 'height=1,width=1,left=-100,top=-100,location=no,toolbar=no,menubar=no,scrollbars=no,resizable=no,directories=no,status=no';
cope.PopupTest.testWindow = window.open("popupTest.htm", "popupTest", cope.PopupTest.params);
if( !cope.PopupTest.testWindow
|| cope.PopupTest.testWindow.closed
|| (typeof cope.PopupTest.testWindow.closed=='undefined')
|| cope.PopupTest.testWindow.outerHeight == 0
|| cope.PopupTest.testWindow.outerWidth == 0
) {
// pop-ups ARE blocked
document.location.href = 'popupsBlocked.htm';
}
else {
// pop-ups are NOT blocked
cope.PopupTest.testWindow.close();
}
The outerHeight and outerWidth are for chrome because the 'about:blank' trick from above doesn't work in chrome anymore.
I'm going to just copy/paste the answer provided here: https://stackoverflow.com/a/27725432/892099 by DanielB . works on chrome 40 and it's very clean. no dirty hacks or waiting involves.
function popup(urlToOpen) {
var popup_window=window.open(urlToOpen,"myWindow","toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, copyhistory=yes, width=400, height=400");
try {
popup_window.focus();
}
catch (e) {
alert("Pop-up Blocker is enabled! Please add this site to your exception list.");
}
}
How about a Promise approach ?
const openPopUp = (...args) => new Promise(s => {
const win = window.open(...args)
if (!win || win.closed) return s()
setTimeout(() => (win.innerHeight > 0 && !win.closed) ? s(win) : s(), 200)
})
And you can use it like the classic window.open
const win = await openPopUp('popuptest.htm', 'popuptest')
if (!win) {
// popup closed or blocked, handle alternative case
}
You could change the code so that it fail the promise instead of returning undefined, I just thought that if was an easier control flow than try / catch for this case.
Check the position of the window relative to the parent. Chrome makes the window appear almost off-screen.
I had a similar problem with popups not opening in Chrome. I was frustrated because I wasn't trying to do something sneaky, like an onload popup, just opening a window when the user clicked. I was DOUBLY frustrated because running my function which included the window.open() from the firebug command line worked, while actually clicking on my link didn't! Here was my solution:
Wrong way: running window.open() from an event listener (in my case, dojo.connect to the onclick event method of a DOM node).
dojo.connect(myNode, "onclick", function() {
window.open();
}
Right way: assigning a function to the onclick property of the node that called window.open().
myNode.onclick = function() {
window.open();
}
And, of course, I can still do event listeners for that same onclick event if I need to. With this change, I could open my windows even though Chrome was set to "Do not allow any site to show pop-ups". Joy.
If anyone wise in the ways of Chrome can tell the rest of us why it makes a difference, I'd love to hear it, although I suspect it's just an attempt to shut the door on malicious programmatic popups.
Here's a version that is currently working in Chrome. Just a small alteration away from Rich's solution, though I added in a wrapper that handles the timing too.
function checkPopupBlocked(poppedWindow) {
setTimeout(function(){doCheckPopupBlocked(poppedWindow);}, 5000);
}
function doCheckPopupBlocked(poppedWindow) {
var result = false;
try {
if (typeof poppedWindow == 'undefined') {
// Safari with popup blocker... leaves the popup window handle undefined
result = true;
}
else if (poppedWindow && poppedWindow.closed) {
// This happens if the user opens and closes the client window...
// Confusing because the handle is still available, but it's in a "closed" state.
// We're not saying that the window is not being blocked, we're just saying
// that the window has been closed before the test could be run.
result = false;
}
else if (poppedWindow && poppedWindow.outerWidth == 0) {
// This is usually Chrome's doing. The outerWidth (and most other size/location info)
// will be left at 0, EVEN THOUGH the contents of the popup will exist (including the
// test function we check for next). The outerWidth starts as 0, so a sufficient delay
// after attempting to pop is needed.
result = true;
}
else if (poppedWindow && poppedWindow.test) {
// This is the actual test. The client window should be fine.
result = false;
}
else {
// Else we'll assume the window is not OK
result = true;
}
} catch (err) {
//if (console) {
// console.warn("Could not access popup window", err);
//}
}
if(result)
alert("The popup was blocked. You must allow popups to use this site.");
}
To use it just do this:
var popup=window.open('location',etc...);
checkPopupBlocked(popup);
If the popup get's blocked, the alert message will display after the 5 second grace period (you can adjust that, but 5 seconds should be quite safe).
This fragment incorporates all of the above - For some reason - StackOverflow is excluding the first and last lines of code in the code block below, so I wrote a blog on it. For a full explanation and the rest of the (downloadable) code have a look at
my blog at thecodeabode.blogspot.com
var PopupWarning = {
init : function()
{
if(this.popups_are_disabled() == true)
{
this.redirect_to_instruction_page();
}
},
redirect_to_instruction_page : function()
{
document.location.href = "http://thecodeabode.blogspot.com";
},
popups_are_disabled : function()
{
var popup = window.open("http://localhost/popup_with_chrome_js.html", "popup_tester", "width=1,height=1,left=0,top=0");
if(!popup || popup.closed || typeof popup == 'undefined' || typeof popup.closed=='undefined')
{
return true;
}
window.focus();
popup.blur();
//
// Chrome popup detection requires that the popup validates itself - so we need to give
// the popup time to load, then call js on the popup itself
//
if(navigator && (navigator.userAgent.toLowerCase()).indexOf("chrome") > -1)
{
var on_load_test = function(){PopupWarning.test_chrome_popups(popup);};
var timer = setTimeout(on_load_test, 60);
return;
}
popup.close();
return false;
},
test_chrome_popups : function(popup)
{
if(popup && popup.chrome_popups_permitted && popup.chrome_popups_permitted() == true)
{
popup.close();
return true;
}
//
// If the popup js fails - popups are blocked
//
this.redirect_to_instruction_page();
}
};
PopupWarning.init();
Wow there sure are a lot of solutions here. This is mine, it uses solutions taken from the current accepted answer (which doesn't work in latest Chrome and requires wrapping it in a timeout), as well as a related solution on this thread (which is actually vanilla JS, not jQuery).
Mine uses a callback architecture which will be sent true when the popup is blocked and false otherwise.
window.isPopupBlocked = function(popup_window, cb)
{
var CHROME_CHECK_TIME = 2000; // the only way to detect this in Chrome is to wait a bit and see if the window is present
function _is_popup_blocked(popup)
{
return !popup.innerHeight;
}
if (popup_window) {
if (popup_window.closed) {
// opened OK but was closed before we checked
cb(false);
return;
}
if (/chrome/.test(navigator.userAgent.toLowerCase())) {
// wait a bit before testing the popup in chrome
setTimeout(function() {
cb(_is_popup_blocked(popup_window));
}, CHROME_CHECK_TIME);
} else {
// for other browsers, add an onload event and check after that
popup_window.onload = function() {
cb(_is_popup_blocked(popup_window));
};
}
} else {
cb(true);
}
};
Jason's answer is the only method I can think of too, but relying on position like that is a little bit dodgy!
These days, you don't really need to ask the question “was my unsolicited popup blocked?”, because the answer is invariably “yes” — all the major browsers have the popup blocker turned on by default. Best approach is only ever to window.open() in response to a direct click, which is almost always allowed.
HI
I modified the solutions described above slightly and think that it is working for Chrome at least.
My solution is made to detect if popup is blocked when the main page is opened, not when popup is opened, but i am sure there are some people that can modify it.:-)
The drawback here is that the popup-window is displayed for a couple of seconds (might be possible to shorten a bit) when there is no popup-blocker.
I put this in the section of my 'main' window
<script type="text/JavaScript" language="JavaScript">
var mine = window.open('popuptest.htm','popuptest','width=1px,height=1px,left=0,top=0,scrollbars=no');
if(!mine|| mine.closed || typeof mine.closed=='undefined')
{
popUpsBlocked = true
alert('Popup blocker detected ');
if(mine)
mine.close();
}
else
{
popUpsBlocked = false
var cookieCheckTimer = null;
cookieCheckTimer = setTimeout('testPopup();', 3500);
}
function testPopup()
{
if(mine)
{
if(mine.test())
{
popUpsBlocked = false;
}
else
{
alert('Popup blocker detected ');
popUpsBlocked = true;
}
mine.close();
}
}
</script>
The popuptest looks like this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Popup test</title>
<script type="text/javascript" language="Javascript">
function test() {if(window.innerHeight!=0){return true;} else return false;}
</script>
</head>
<body>
</body>
</html>
As i call the test-function on the popup-page after 3500 ms the innerheight has been set correctly by Chrome.
I use the variable popUpsBlocked to know if the popups are displayed or not in other javascripts.
i.e
function ShowConfirmationMessage()
{
if(popUpsBlocked)
{
alert('Popups are blocked, can not display confirmation popup. A mail will be sent with the confirmation.');
}
else
{
displayConfirmationPopup();
}
mailConfirmation();
}
function openPopUpWindow(format)
{
var win = window.open('popupShow.html',
'ReportViewer',
'width=920px,height=720px,left=50px,top=20px,location=no,directories=no,status=no,menubar=no,toolbar=no,resizable=1,maximize:yes,scrollbars=0');
if (win == null || typeof(win) == "undefined" || (win == null && win.outerWidth == 0) || (win != null && win.outerHeight == 0) || win.test == "undefined")
{
alert("The popup was blocked. You must allow popups to use this site.");
}
else if (win)
{
win.onload = function()
{
if (win.screenX === 0) {
alert("The popup was blocked. You must allow popups to use this site.");
win.close();
}
};
}
}
As far as I can tell (from what I've tested) Chrome returns a window object with location of 'about:blank'.
So, the following should work for all browsers:
var newWin = window.open(url);
if(!newWin || newWin.closed || typeof newWin.closed=='undefined' || newWin.location=='about:blank')
{
//POPUP BLOCKED
}

In a $.ajax callback, how do I distinguish an unreachable server from a user navigating away?

Situation:
You've got a few $.ajax requests to the server that are still running. They all error out with xhr.status === 0 and xhr.readyState === 0.
Possible causes:
The server is down (EDIT: as in unreachable - no headers are returned or anything).
The user clicked a link/refreshed the page/otherwise navigated away.
I would like to pop up a dialog in the first case, but ignore the second. How do I distinguish between these two in my complete method? The complete method is fired before the $(window).unload event, so I can't use that to determine if the user clicked away. I could also use a setTimeout to try to wait for the next page to load, but that's dirty. Is there something else I can do?
(This answer is an abstract of another answer, for clarity's sake by the OP's request)
If a window level flag isn't working, the next dom level event to test before $(window).unload is window.onbeforeunload. Is that a viable option?
Around your AJAX method:
var running = true;
// do this only once!!!
var _obunload = ( window.onbeforeunload )? window.onbeforeunload: function(){};
window.onbeforeunload = function()
{
_obunload.call( window );
running = false;
}
xhr.onreadystatechange = function()
{
if( !xhr.status && !xhr.readyState && running )
{
// warning! warning! danger Will Robinson!
// there was a server error
}
else if( !xhr.status && !xhr.readyState )
{
// user did something... Who gives?
}
running = false;
}
You can check for a timeout response from the server:
timeout:500,
error: function(jqXHR, textStatus, errorThrown) {
if(textStatus==="timeout") {
alert("got timeout");
} else {
// Some other error
}
}
Idea 3
Well, there is always the possibility of faking a delay from the non-existent server:
var running = true;
xhr.onreadystatechange = function()
{
if( !xhr.status && !xhr.readyState )
{
// wait a short while to see whether the page is unloading.
setTimeout( unloadTest, 250 );
}
else
{
running = false;
}
}
function unloadTest()
{
// running will be set to false by onbeforeunload, which means this
// should only be true if there was some form of server error.
if( running ) // Regnad? Robin Williams?
}
Then, elsewhere:
// (using generic JS, you can use $(window).bind( 'beforeunload' ...
window.onbeforeunload = function()
{
running = false;
}
Idea 2
Well, if below isn't working, the next dom level event to test before $(window).unload is window.onbeforeunload. Is that a viable option?
Around your AJAX method:
var running = true;
xhr.onreadystatechange = function()
{
if( !xhr.status && !xhr.readyState && running )
{
// warning! warning! danger Will Robinson!
// there was a server error
}
else if( !xhr.status && !xhr.readyState )
{
// user did something... Who gives?
}
running = false;
}
Then, elsewhere:
// (using generic JS, you can use $(window).bind( 'beforeunload' ...
window.onbeforeunload = function()
{
running = false;
}
Original post (apparently is not working)
Why not set a flag on the window itself?
<html>
<script type="text/javascript">
// window.currentTime will update *first* after every page refresh.
window.currentTime = new Date().getTime()
</script>
<!-- continue as normal -->
Then, when you're about to call $.ajax:
// winTime is bound to window.currentTime at the time of the original query.
var winTime = window.currentTime;
// using onreadystatechange because it looks like you're looking for that in your
// question. This can be easily adapted to $.ajax, however.
xhr.onreadystatechange = function()
{
if( !xhr.status && !xhr.readyState && winTime == window.currentTime )
{
// warning! warning! danger Will Robinson!
// there was a server error
}
else if( !xhr.status && !xhr.readyState )
{
// user did something... Who gives?
}
}

Categories