hassen zouari hassen zouari - 7 months ago 27
Javascript Question

How to check if page exists using Javascript?

I'm using Javascript and i want check if a page/url (of another domain exist)

I tried this but it doesn't work

$.ajax({
type: 'HEAD',
url: 'http://google.com',
success: function() {
alert('1');
},
error: function() {
alert('0');
}
});


it show me this error


XMLHttpRequest cannot load http://google.com/. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localads-4u.com' is therefore not allowed
access.


Note : the tested script is online

Answer

I'm using Javascript and i want check if a page/url (of another domain exist)

If only requirement is to check if the external resource is available, one possible workaround for No 'Access-Control-Allow-Origin' header is present on the requested resource. response from AJAX is to instead request .html document or url at src of <img> element. Check onerror handler for GET http://example.com/ net::ERR_NAME_NOT_RESOLVED

var img = new Image;
img.onload = function(e) {
  console.log(this, this.src)
}

img.onerror = function(e) {
  console.log(e, this)
};

img.src = "http://example.com";
Comments