简体   繁体   中英

read the HTTP header to check for 404 with jQuery without performing an ajax request

Is there a way to read the HTTP header with jQuery without performing a .ajax request and reading xhr.status ?

Along similar lines to the popular Google Analytics addon ( gaAddons ) I wish to track 404s on my site. Unfortunately, I have inherited a legacy system and 404s do not have a unique URL.

Is it possible to read the HTTP header using jQuery?

I don't think this is possible - they are not exposed to JavaScript. An AJAX request is the obvious workaround - not sure why you're against this.

More info in this question: Accessing the web page's HTTP Headers in JavaScript

If you have access to the 404 error page, you could inject javascript into the 404 page that can send page details like, url, time etc to server through ajax [but it's point less if they are in server logs]. But then, this script can be exploited.

You might be able to do something like this in jQuery:

if ( $('meta[content="Not Found - The URL you requested could not be found."]').length>0 ) {
    /* do something about it */
}

This assumes that the delivery engine has put the following meta tag in the header of the page. Tumblr does this, for example. Your own system may put a different meta tag or you could design your system to deliver some such meta tag.

<meta name="description" content="Not Found - The URL you requested could not be found." />

Of course, all this is really doing is checking the meta header which offers a page summary. But you could take advantage of the mechanism in your own environment.

While doing site analytics i had to record errors separately.

Similar to @Octopus suggestion i added a meta tag to 404 and 500 pages.

<meta name="error" content="404">

On the client i then checked if this meta tag existed like so:

<script>
  meta = document.getElementsByTagName('meta');

  for (i=0; i< meta.length; i++) {

    if(meta[i].name == 'error'){
       alert('This page returned a ' + meta[i].content + ' error');   
    }

  }

</script>

Unfortunately i had to use vanilla JS to achieve this.

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