JavaScript/jQuery check broken links
If the files are on the same domain, then you can use AJAX to test for their existence as Alex Sexton said; however, you should not use the GET
method, just HEAD
and then check the HTTP status for the expect value (200, or just less than 400).
Here's a simple method provided from a related question:
function urlExists(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
callback(xhr.status < 400);
}
};
xhr.open('HEAD', url);
xhr.send();
}
urlExists(someUrl, function(exists) {
console.log('"%s" exists?', someUrl, exists);
});
Checking if a URL is broken in Javascript
I'd recommend to use jQuery for correct cross-browser ajax requests:
function UrlExists(url, cb){
jQuery.ajax({
url: url,
dataType: 'text',
type: 'GET',
complete: function(xhr){
if(typeof cb === 'function')
cb.apply(this, [xhr.status]);
}
});
}
Usage:
UrlExists('/path/script.pl', function(status){
if(status === 200){
// file was found
}
else if(status === 404){
// 404 not found
}
});
Detect broken image and get src's using jquery
.error
is deprecated, need to use .on('event'
instead.
Allow error
is asynchronous, your code is not waiting for images to get loaded to send final report of broken images. Also empty src attribute on img will not trigger error or success, you need to ignore or add them separately. I have ignored them in below code.
$(document).ready(function() {
//Check Image Error var i = 0; var brokenSrc = [];
var totalImagesOnPage = $('img').not( "[src='']" ).length;
$('img').on('load', function() { increaseCount(); }).on('error', function() { var link = $(this).attr('src'); console.log('broken link : ' + link); brokenSrc.push(link); increaseCount(); });
function increaseCount() { i++; if (i == totalImagesOnPage) { finishedLoadingImages(); } }
function finishedLoadingImages() { console.log("Broken images ::", brokenSrc); $.ajax({ type: "POST", url: '/', data: { imageData: { current_url: window.location.href, broken_src: brokenSrc } }, success: function(result) { console.log(result); } }); }
});
<!DOCTYPE html><html><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> <script src="https://code.jquery.com/jquery-3.1.0.js"></script></head><body>
<img src="" /><img src="http://google.com" /><img src="https://dab1nmslvvntp.cloudfront.net/wp-content/uploads/2014/05/1399880336proe-pic_400x400-96x96.jpg" /><img src="https://simplyaccessible.com/wordpress/wp-content/themes/sa-wp-2014/images/logo.svg"/>
</body></html>
Detect links to non-existent websites using JavaScript
Due to Same Origin Policy, you would need to create a proxy on a server to access the site and send back its availability status - for example using curl:
<?PHP
$data = '{"error":"invalid call"}'; // json string
if (array_key_exists('url', $_GET)) {
$url = $_GET['url'];
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
/* Get the HTML or whatever is linked in $url. */
$response = curl_exec($handle);
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
curl_close($handle);
$data = '{"status":"'.$httpCode.'"}';
if (array_key_exists('callback', $_GET)) {
header('Content-Type: text/javascript; charset=utf8');
header('Access-Control-Allow-Origin: http://www.example.com/');
header('Access-Control-Max-Age: 3628800');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
$callback = $_GET['callback'];
die($callback.'('.$data.');'); //
}
}
// normal JSON string
header('Content-Type: application/json; charset=utf8');
echo $data;
?>
Now you can ajax to that script with the URL you want to test and read the status returned, either as a JSON or JSONP call
The best client-only workaround I have found, is to load a site's logo or favicon and use onerror/onload but that does not tell us if a specific page is missing, only if the site is down or have removed their favicon/logo:
function isValidSite(url,div) {
var img = new Image();
img.onerror = function() {
document.getElementById(div).innerHTML='Site '+url+' does not exist or has no favicon.ico';
}
img.onload = function() {
document.getElementById(div).innerHTML='Site '+url+' found';
}
img.src=url+"favicon.ico";
}
isValidSite("http://google.com/","googleDiv")
Related Topics
How to Update React Context from Inside a Child Component
Disable Hover Effects on Mobile Browsers
JavaScript Getelementbyid Based on a Partial String
What Is the Meaning of an Underscore in JavaScript Function Parameter
How to Prevent Moment.Js from Loading Locales with Webpack
Query Firestore Database for Document Id
Case Insensitive String Replacement in JavaScript
How to Use Blob Url, Mediasource or Other Methods to Play Concatenated Blobs of Media Fragments
How to Load Image Files with Webpack File-Loader
How to Use Cors to Implement JavaScript Google Places API Request
Vue V-On:Click Does Not Work on Component
How to Get the Containing Form of an Input
How Is a Promise/Defer Library Implemented
Es6 Modules Implementation, How to Load a JSON File
How to Detect Right Mouse Click + Paste Using JavaScript
Given a String Describing a JavaScript Function, Convert It to a JavaScript Function