how do I detect if window.location failed?

随声附和 提交于 2019-11-29 06:56:16

Finally got it to work using a "workaround" that is not a generic solution as I originally hoped:

I am using the fact that the link I am trying to open is a custom url scheme (e.g. myxx://localhost) on mobile, and if it fails, the action I want to perform is a redirection to a standard appstore URL (os-specific). The workaround tries to open the custom URL, and if it fails, the timeout function kicks in shortly after, and opens an alternative url:

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

The downside is that when the customURL fails, a standard safari browser shows a message box that the site could not be opened, but at least it still redirects the user to the appstore.

Not really possible, because when window.location = someURL is executed, before the URL is even tested, your document is removed from the window. You have no code remaining that could test if it worked.

If the link is on the same origin, you may issue an XMLHttpRequest to test if the page is reachable but there doesn't seem to be a way to test if a page isn't requestable just due to cross origin request or because the URL is wrong.

For a general document, I don't know any way to test if a foreign origin page is reachable (but it can be done for an image using the onload event handler).

you can check if page exists using ajax. didn't test 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!"); }  
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!