How to determine if window.location failed?

how to check if the call to window.location caused because the given url was invalid, etc.? Is there some kind of event that I can set on a window object or on some other object that can catch it?

+6
source share
3 answers

Finally, he started working using a “workaround”, which is not the general solution I originally hoped for:

I use the fact that the link I'm trying to open is a custom URL scheme (e.g. myxx: // localhost) on the mobile device, and if it fails, the action I want to perform is redirecting to the standard application URL (os-specific). The workaround is trying to open a custom URL, and if it doesn’t work, the timeout function starts shortly afterwards and opens an alternate URL:

setTimeout(function() { window.location=alternateUrl; }, 25); window.location = customUrl; 

The downside is that when a customURL fails, the standard Safari browser displays a message box that the site cannot be opened, but at least it redirects the user to the AppStore.

+8
source

This is impossible because when window.location = someURL is executed before the URL is even tested, your document will be deleted from the window. You have no code left to check if it worked.

If the link has the same origin, you can send an XMLHttpRequest to check if the page is available, but there isn’t any way there is a way to check if the page is being requested just because of a cross origin request or because of an incorrect URL.

For a general document, I don’t know how to check if a page with a foreign original is available (but this can be done for the image using the onload handler).

+3
source

you can check if the page exists using ajax. didn't test the code, but it should work.

 var rekuest= new XMLHttpRequest(); rekuest.open('GET', 'http://www.thisdoesnotexits.org', true); rekuest.send(); if (rekuest.status === "404") {alert("not exist!"); } 
+1
source

Source: https://habr.com/ru/post/952360/


All Articles