[英]Detect links to non-existent websites using JavaScript
我正在嘗試使用JavaScript檢測網頁上的損壞鏈接,但遇到了問題。 有什么方法可以使用客戶端JavaScript檢測不存在的URL,如下所示?
function URLExists(theURL){
//return true if the URL actually exists, and return false if it does not exist
}
//test different URLs to see if they exist
alert(URLExists("https://www.google.com/")); //should print the message "true";
alert(URLExists("http://www.i-made-this-url-up-and-it-doesnt-exist.com/")); //should print the message "false";
由於同源策略的緣故,您需要在服務器上創建代理以訪問站點並發送其可用性狀態(例如,使用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;
?>
現在,您可以使用要測試的URL來對該腳本進行Ajax,並以JSON或JSONP調用的形式讀取返回的狀態
我發現最好的僅客戶端解決方案是加載站點的徽標或圖標,並使用onerror / onload,但這不會告訴我們是否缺少特定頁面,僅當站點關閉或已刪除其圖標/徽標時:
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")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.