Building The Conversation

Client Side 404 checking using JSON-P

Firstly a disclaimer - this code was written as part of a funday friday. It is not on production and we wouldn’t recommend to anyone.

At The Conversation we publish hundreds of articles a month and we were thinking “It’d be great to have a way to validate links on articles prior to publication!”

We didn’t want to write any server side code and client side checking wouldn’t work due to cross site scripting issues – or would it…

The hack

We knew you could make a request using JSONP to any domain (the same way you’d load a list of tweets). We found that by using the error state you can determine whether it was a parser error (the document was found but was not JS) or some other error (the document most likely didn’t exist).

This turned out to be an excellent way to do client side link validation.

The code:

    $("a").each ->
      link = $(this)
        url: link.attr("href")
        dataType: "jsonp"
        jsonp: ""
        timeout: 8000
        success: (data, status) ->
        error: (XHR, textStatus, errorThrown) ->
          if textStatus == "parsererror"

We also found that we could rescue Script errors on window to lead to less console errors:

    $(window).error (error) ->
      if error.originalEvent.message == "Script error."

The styling was done exclusively with CSS (no additional markup) using content: attr(href): code

This code works in Chrome/Safari (untested in Firefox).

Owning up…

Ok so it was in production for a while.

We pulled it when we switched to SSL for editors as it caused issues with mixed content warnings. I have no idea whether it would cause security vulnerabilities (if one of the sites returned valid JS/JSONP). YMMV