Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

window.open.. A way to tell if the window had a timeout or 404?

Tags:

javascript

I've been making a webpage that uses a sort of... external survey taking. I was wonder if when using the window.open method, can you tell if your new window had a 404 or the page timedout trying to load?

Here is what I have so far:

child = window.open(href, 'window');
        setTimeout(function() {
            // Do some backend processing if child window is still open and no 404 / timeout
        }, 10000);
like image 403
Wilson212 Avatar asked Nov 05 '22 08:11

Wilson212


2 Answers

That's a pretty hard thing to do. You have to deal with security issues (cross domain access is forbidden in JS). But I think this function can do the trick:

child = window.open(href, 'window');
        setTimeout(function() {
            try {
                var foo = child.location;
            }
            catch (err) {
                // It has loaded. Manage that.
                return;
            }
            // Still loading. Code here.
            }
        }, 10000);

Explanation: try to access the location element of the child window. If the window has loaded, trying to access it will throw an exception (cross domain JS access is forbidden) so you manage that. But if you can access the location that will probably mean it's still loading.

The main problem is that, with this code, you can only distinguish when it's loading or not, so I suppose you could only check for timeout. I think that checking 404 error is almost impossible as the JS security restrictions don't allow you to get the location or content of an external page.

like image 135
gjulianm Avatar answered Nov 10 '22 20:11

gjulianm


Have a look at cross-domain ajax requests:

http://james.padolsey.com/javascript/cross-domain-requests-with-jquery/

There are a few ways you could employ it depending on how the remote site is structured, but at the very least you could check that the page exists before launching the popup (though this won't guarantee that it loads in the popup).

Alternately, have the popup load a local script (php, etc) which first does a cUrl or other remote check... have it check the headers returned, and then - if all is good - it sends headers to forward to the remote site. If an error code is returned, then you have the popup window load a local html/js page that has a script that can speak to the opener window to let it know that it failed.

like image 23
Ben D Avatar answered Nov 10 '22 19:11

Ben D