简体   繁体   中英

Try/Catch for Javascript in mobile safari?

Can I wrap a try/catch around the opening of a URL in mobile safari? I know the question has been asked a number of different ways but essentially what I'm after is the trapping of bad URLs or the detection of when a specific URL cannot be opened by the browser.

If the URL is within the same domain, then you can use an XMLHttpRequest to determine if it returns a valid response.

eg

var xhr = new XMLHttpRequest();

function handler(){
  if (xhr.readyState != 4)  { return; }
  if (xhr.status != 200) { return "THIS IS A BAD LINK"}
}

if (xhr != null) {
    xhr.open("GET", URL_YOU_ARE_TESTING, true);
    xhr.send();
    xhr.onreadystatechange = handler;
}

However this won't work for links to other sites (which is what I guess you want) due to the browser's same origin policy . I don't believe there is a javascript solution for this case.

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