terça-feira, 12 de agosto de 2014

A Better 404 Page

A Better 404 Page


A lot of humorous 404 pages have been common recently: delicately crafted memes, humorous GIFs, even a peculiar interactive game. But if a 404 doesn’t assistance your visitors, afterwards what’s a point?


A caller could find themselves on a 404 page for one of many reasons: a mistyped address, a bad couple from somewhere else, a deleted page or calm that has changed elsewhere. While we can forestall errors from changed pages with redirects, we can’t control people’s mistakes.


Being Helpful


People who land on your website are looking for a content, customarily around a link. They would have clicked that couple awaiting one thing, so because uncover them a hand-drawn panda? Instead, your 404 page should get them to where they need to be.


This problem isn’t new, and we’ve seen a lot of ideas on how to hoop it. Showing a hunt form or joining to a home page is reasonable. Yet those are pacifist solutions that don’t solve a visitor’s problem. A some-more ensue ensue would be to theory where a caller dictated to go and advise that page.


Suggesting The Right Page


One ensue to advise a right page is to hunt for it yourself and benefaction a result. Luckily, we don’t have to write a hunt engine to do this (although, if we have one handy, good for you!). Instead, we can use Google’s Custom Search API1.


We can use Google’s Custom Search API to advise a right page.
We can use Google’s Custom Search API to advise a right page.

Google’s Custom Search API is a apparatus for acid within an particular website. When set up, it enables we to collect what it considers to be a best compare from your website. It does need a hunt phrase, though. So, to give Google something to hunt with, we’ll use a trail of a URL that a user is now on.


Caveat: Limits Abound


Before jumping into a “how to” part, it’s value observant that a giveaway tier for this API has a extent of 100 calls per day. You competence wish to go light on a contrast while operative on it. we managed to bake by a 100 calls in reduction than an hour, and we had to handle partial of it together though saying a outcome compartment a subsequent day.


While someone with a tiny website competence be excellent with this limit, paid upgrades are available. Google’s API support mentions a cost of $5 per 1000 queries2 and adult to 10,000 queries per day.


Setting Up


Before regulating a Custom Search API, we need to let Google know who we are and get some entrance keys.


Search Engine ID


We need to go by a few stairs before we can fly by those 100 API requests. First, register your site-specific hunt engine3.


  • Select “Add.”

  • Input your website’s URL (yoursite.com) in “Sites to search.”

  • Hit “Create.”

You now need to find your “Search engine ID.” Click “Edit” on a hunt engine that we created, afterwards a “Search engine ID” button. Take note of that code!


Setting adult a Google’s Custom Search API.4
Setting adult a Google’s Custom Search API. (View vast version5)

Developer API Access


Next, go to a Developers Console6.


If we don’t nonetheless have a project, name a “New Project” choice and fill in a form.


Under “APIs,” activate a “Custom Search API” by switching a “Off” symbol to “On.” Then, name “Credentials,” afterwards “Create New Key,” and select a “Browser Key” option. Take note of a API key!


7
(View vast version8)

JavaScript


Armed with both a hunt engine ID and an API key, we can now start attack a API. The formula next requires jQuery9. It does some AJAX JSON stuff, so I’d rather gaunt on a horizon to safeguard that it works opposite browsers.


Before formulating functions, we should cruise a sourroundings that a formula will run in. Because we’re essay JavaScript on a front end, a formula competence run alongside other plugins and scripts. So, let’s build a small space to clean apart a functions from all else:


function createCustomSearch() 
// Private variables and methods here


Within a customSearch object, we can conclude methods and variables safely divided from a tellurian context. First, let’s set adult some variables to use later:


function createCustomSearch() 
// Some private variables for this object
var context = this;
var dialog = document.querySelector('dialog');
// Your keys
var engineID = 'YOUR_ENGINE_ID';
var apiKey = 'YOUR_API_KEY';


Replace a keys with those we generated earlier.


Initially, we settle a internal context by storing this in a variable. We’ll use this to entrance a showDialog process later.


Trying A Search


First, we’ll supplement a process that tries a tradition search:


function customSearchConstructor() 
// Some private variables for this object
var context = this;
var dialog = document.querySelector('dialog');
// Your keys
var engineID = 'YOUR_ENGINE_ID';
var apiKey = 'YOUR_API_KEY';
this.trySearch = function(phrase)
var queryParams =
cx: engineID,
key: apiKey,
num: 10,
q: phrase,
alt: 'JSON'

var API_URL = 'https://www.googleapis.com/customsearch/v1?';
// Send a ask to a tradition hunt API
$.getJSON(API_URL, queryParams, function(response)
if (response.items response.items.length)
console.log(response.items[0].link);

);
;


This trySearch process takes a word and sends it along with your keys as a ask to Google’s API. The response is afterwards checked, and a initial couple that it finds will be logged to a console. You would call it like so:


var customSearch = new customSearchConstructor();
customSearch.trySearch('cat');

Assuming that your website contains pages about cats (and whose doesn’t?), we should see something logged in your console.


Getting The Search Phrase


Next, we’ll write some formula to get a trail from a URL of a page. This trail will turn a hunt phrase.


$(document).ready(function() 
var customSearch = new customSearchConstructor();
var trail = window.location.pathname;
var word = decodeURIComponent(path.replace(//+/g, ' ').trim());
customSearch.trySearch(phrase);
);

Within a jQuery ready method, we’ll collect adult a pathname partial of a stream URL and emanate a hunt word from it. We’ll decode a URI, reinstate any brazen slashes with spaces, and send a outcome to a trySearch method.


Replacing Strings With JavaScript


One accessible thing to know is how to reinstate a tellurian unchanging countenance in JavaScript. This one is a set of matches distant by pipes:


//+/g

The initial and final brazen slashes (/) are there to enclose a expression. Within it, we shun a backslash impression (/) so that it is treated as an tangible character. The + will compare any instances of mixed slashes, and a g afterwards tells it to reinstate each instance in a string.


Showing The Redirect


In my initial version, we had a page route immediately. That was fun though not a good knowledge for a visitor. The page would load, flutter and burst elsewhere.


An choice ensue is to benefaction a choice as an conceal and as a couple that a caller can click. This way, a caller improved understands what has happened and sees a transparent ensue to proceed. And they will have a choice not to ensue if a outcome doesn’t fit them.


Other Approaches


Showing a singular outcome is one ensue to go about this, though it would be value deliberation some-more than a initial result. If we wish to give a caller some-more options, afterwards your 404 page could uncover all of a returned pages as a set. Depending on a peculiarity of a formula from a tradition search, this competence be better.


For this example, let’s assume that a initial outcome returned is always a many relevant, and we’ll benefaction a singular choice in a form of a dialog overlay.


Also, cruise cases in that no formula are returned. Ensure that your 404 page contains some useful summary or content.


Starting A Dialog


If we find a result, let’s uncover it as a modal that prompts a user. To assistance with this, we’ll be means to use a new dialog10 element11 in a nearby future. Originally dictated for discourse from movies, a component is behind and can now uncover any calm that needs to be popped adult in front of other content. In other words, we now have a internal HTML5 modal element.


Let’s conclude a dialog in HTML:


dialog
h2
Hey, is this what we meant?
camber class="suggestion"/span
camber class="nope"No thanks/span
/h2
/dialog

Polyfill For Older Browsers


Before job a JavaScript that will uncover and censor this dialog, we need to cruise comparison browsers. The dialog component is really new and so isn’t upheld everywhere. To repair this, we can use a useful polyfill supposing by Google12.


This polyfill requires a small JavaScript. The following outmost book will need to be called before we emanate a dialog:


script src="https://cdn.rawgit.com/GoogleChrome/dialog-polyfill/master/dialog-
polyfill.js"/script

This book includes a registerDialog process that wraps a dialog selector with a few accessible functions that imitate a internal API. We can use it in a customSearch object:


function createCustomSearch() 

var dialog = document.querySelector('dialog');
// Apply a polyfill
dialogPolyfill.registerDialog(dialog);



Showing And Hiding


We now have a dialog element, with additional methods combined by a registerDialog polyfill. Let’s supplement some methods to uncover and censor a element:


function createCustomSearch() 

this.showDialog = duty (url)
var suggestedLink = $('');
// Verify that a suggested URL is from this domain
var hostname = new RegExp(location.host);
if (hostname.test(url))
suggestedLink.attr('href', url);
suggestedLink.text(url);
$('dialog .suggestion').html(suggestedLink);
dialog.showModal();

;
this.hideDialog = duty ()
dialog.close();
;


We’ve got dual methods here. The first, showDialog, takes a URL, places it in a dialog element, and calls a showModal process supposing by a polyfill.


To strengthen ourselves, we’re verifying a URL. Because we’re awaiting this book to lapse another page from a same website, we determine that a returned URL’s horde name and a internal website’s horde name are a same.


The URL is afterwards used to beget an anchor, that we place in a dialog HTML.


The second method, hideDialog, hides a modal regulating a possess close method.


Styling The Dialog


Lastly, let’s supplement some style. The default modal character is a bit too boxy. We’ll make it subtler and give it a dim credentials with some CSS:


dialog 
display: none;
position: absolute;
top: 0;
right: 0;
left: 0;
text-align: center;
color:
border: none;
background: none;


dialog[open]
display: block;


dialog[open]:before
position: fixed;
z-index: -1;
top: 0;
right: 0;
bottom: 0;
left: 0;
content: '';
background: rgba(0,0,0,.8);


dialog camber
display: block;


dialog span.suggestion
font-size: 1.75em;
line-height: 2.5em;


dialog h2
line-height: 1.5em;
padding-top: 2em;


dialog a
padding: .25em;
border-radius: .25em;
background: rgba(200,200,255,.9);


dialog .nope
font-size: .75em;
cursor: pointer;
color:


We’re referring directly to a dialog in this CSS. For some-more flexibility, we competence cite to impute to it by a class.


Tweak a several styles to fit your design. The categorical thought of this CSS is to conclude how a dialog looks, and have it display: block when given a category of open. The other styles, from position to color, are wholly adult to you.


Wiring In The Search


Next, we need to adjust that trySearch process from progressing to use a dialog. We do this by fixation a showDialog process call within a JSON response callback. Here’s a full script:


// ![CDATA[
function customSearchConstructor()
// Some private variables for this object
var context = this; // Keeps a primogenitor context accessible so that we can call internal methods
var dialog = document.querySelector('dialog');
// Apply a polyfill
dialogPolyfill.registerDialog(dialog);
// Your keys
var engineID = 'YOUR_ENGINE_ID';
var apiKey = 'YOUR_API_KEY';
this.trySearch = function(phrase)
var queryParams =
cx: engineID,
key: apiKey,
num: 10,
q: phrase,
alt: 'JSON'

var API_URL = 'https://www.googleapis.com/customsearch/v1?';
// Send a ask to a tradition hunt API
$.getJSON(API_URL, queryParams, function(response)
if (response.items response.items.length)
context.showDialog(response.items[0].link);

);
;
this.showDialog = duty (url)
var suggestedLink = $('');
// Verify that a suggested URL is from this domain
var hostname = new RegExp(location.host);
if (hostname.test(url))
suggestedLink.attr('href', url);
suggestedLink.text(url);
$('dialog .suggestion').html(suggestedLink);
dialog.showModal();

;
this.hideDialog = duty ()
dialog.close();
;

$(document).ready(function()
var customSearch = new customSearchConstructor();
var trail = window.location.pathname;
var word = decodeURIComponent(path.replace(//+/g, ' ').trim());
customSearch.trySearch(phrase);
$('dialog .nope').click(function()
customSearch.hideDialog();
);
);
// ]]

Live Demo


You can see this formula in movement on my 404 page13. Typing something like …/mac/plus/article/ will outcome in a 40414 that recommends a CSS Mac Plus blog.


Fallbacks And Other Strategies


API boundary aside, it’s probable that a compare isn’t found for a mistyped URL. In this case, display a caller some useful calm would be a good idea. Depending on your website, we could uncover new articles or recently updated pages or maybe even a tradition hunt box.


Google’s Custom Search Engine15 gives us a choice to get some embedding code. Select your existent engine and afterwards a “Get code” symbol to find this. Whatever calm we confirm to uncover as a fallback, it will be improved for your visitors than display a humorous picture. It competence not be as most fun, though it will assistance visitors find what they need.


I wish you’ve enjoyed this article. If we wish to share it, greatfully double-check that a URL is correct. Or don’t. I’m certain it’ll be fine.


Front page picture credits: OpenSource.com16


(ds, il, al)


Footnotes


  1. 1 https://developers.google.com/custom-search/

  2. 2 https://developers.google.com/custom-search/json-api/v1/overview

  3. 3 https://www.google.com/cse/manage/all

  4. 4 http://www.smashingmagazine.com/wp-content/uploads/2014/08/02_new_engine_form-large-opt.jpg

  5. 5 http://www.smashingmagazine.com/wp-content/uploads/2014/08/02_new_engine_form-large-opt.jpg

  6. 6 https://console.developers.google.com/project

  7. 7 http://www.smashingmagazine.com/wp-content/uploads/2014/08/04b_api_key-large-opt.jpg

  8. 8 http://www.smashingmagazine.com/wp-content/uploads/2014/08/04b_api_key-large-opt-500×169.jpg

  9. 9 http://jquery.com/

  10. 10 http://updates.html5rocks.com/2013/09/dialog-element-Modals-made-easy

  11. 11 https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dialog

  12. 12 https://github.com/GoogleChrome/dialog-polyfill

  13. 13 http://hop.ie/smashing/404/

  14. 14 http://hop.ie/mac/plus/article/

  15. 15 https://www.google.com/cse/

  16. 16 https://www.flickr.com/photos/opensourceway/6554315319/

↑ Back to topShare on Twitter



A Better 404 Page

Nenhum comentário:

Postar um comentário