简体   繁体   中英

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. 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.".

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.

EDIT : The url is in valid format only, but the website domain is wrong. 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. Perhaps you should verify that it is a valid URL before attempting to access it.

Use a regular expression to validate the url syntax before passing it to safari. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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