简体   繁体   English

JavaScript:当打开的网址无效时,防止显示警报

[英]JavaScript : Prevent showing alert when the url being opened is invalid

I have a requirement where I have to open a URL from html page. 我有一个必须从html页面打开URL的要求。 But, before I open the URL I cannot determine if the URL is a valid or not, so when I try to open a invalid url, the webpage throws an alert saying "Safari cannot open the page because the address is invalid.". 但是,在打开URL之前,我无法确定URL是否有效,因此当我尝试打开无效的URL时,网页会发出警告,提示“ Safari无法打开页面,因为地址无效。”。

I understand it is designed for a reason, but is there anyway to prevent showing this alert, when the url is not a valid one. 我了解它是出于某种原因而设计的,但是无论如何,当URL不是有效的URL时,是否有可能阻止显示此警报。

EDIT : The url is in valid format only, but the website domain is wrong. 编辑:该URL仅采用有效格式,但该网站域错误。 I think, regex will not help in this case. 我认为,正则表达式在这种情况下无济于事。

You can't prevent Safari from presenting that alert when you attempt to access an invalid URL. 当您尝试访问无效的URL时,您无法阻止Safari显示该警报。 Perhaps you should verify that it is a valid URL before attempting to access it. 也许您应该在尝试访问它之前验证它是有效的URL。

Use a regular expression to validate the url syntax before passing it to safari. 在将其传递到Safari之前,请使用正则表达式来验证url语法。 For example: 例如:

^(http(?:s)?\:\/\/[a-zA-Z0-9]+(?:(?:\.|\-)[a-zA-Z0-9]+)+(?:\:\d+)?(?:\/[\w\-]+)*(?:\/?|\/\w+\.[a-zA-Z]{2,4}(?:\?[\w]+\=[\w\-]+)?)?(?:\&[\w]+\=[\w\-]+)*)$

If this does not work for you, you can find many other url validation regular expressions to validate your URL. 如果这对您不起作用,则可以找到许多其他url验证正则表达式来验证您的URL。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM