javascript 我如何检测 window.location 是否失败?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18404148/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how do I detect if window.location failed?
提问by Sagi Mann
how do I check if a call to window.location failed because the given URL was invalid, etc? Is there some event I can set on the window object or on some other object that can catch this?
我如何检查对 window.location 的调用是否因为给定的 URL 无效等而失败?是否可以在 window 对象或其他可以捕获此事件的对象上设置某些事件?
回答by Sagi Mann
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:
我使用的事实是,我尝试打开的链接是移动设备上的自定义 url 方案(例如 myxx://localhost),如果失败,我要执行的操作是重定向到标准应用商店 URL(os -具体的)。解决方法尝试打开自定义 URL,如果失败,则超时功能会在不久之后启动,并打开一个备用 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.
不利的一面是,当 customURL 失败时,标准的 safari 浏览器会显示一个无法打开该站点的消息框,但至少它仍会将用户重定向到应用商店。
回答by Denys Séguret
Not really possible, because when window.location = someURLis 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.
不太可能,因为在window.location = someURL执行时,甚至在测试 URL 之前,您的文档就会从窗口中删除。您没有剩余的代码可以测试它是否有效。
If the link is on the same origin, you may issue an XMLHttpRequestto 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.
如果链接来自同一个源,您可以发出XMLHttpRequest来测试页面是否可访问,但似乎没有一种方法可以测试页面是否仅由于跨源请求或 URL 而不可请求是错的。
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 onloadevent handler).
对于一般文档,我不知道有什么方法可以测试外部来源页面是否可访问(但可以使用onload事件处理程序对图像进行测试)。
回答by Davor Mlinaric
you can check if page exists using ajax. didn't test code, but it should work.
您可以使用ajax检查页面是否存在。没有测试代码,但它应该可以工作。
var rekuest= new XMLHttpRequest();
rekuest.open('GET', 'http://www.thisdoesnotexits.org', true);
rekuest.send();
if (rekuest.status === "404") {alert("not exist!"); }

