Gravatar is a free service that lets you associate a profile picture with your email address. Gravatar makes each user’s profile image available via a specially formatted URL. For example, Figure 18.3 shows the Gravatar of one of our test accounts.
See the end of the URL? That is a unique identifier generated from
the user’s email address. This identifier is called a
hash and is easy to generate with the help of a
third-party library called crypto-js
.
Add crypto-js
to your project using npm
:
npm install --save-dev crypto-js
crypto-js
is now installed in your
project’s local node_modules
folder and ready for use.
When you create strings in JavaScript, you often need to concatenate the string with some other value. ES6 provides a better way to create strings that include values from expressions and variables, called template strings. You will use this feature to create the URL for accessing Gravatar images.
In dom.js, add another import
statement for
the md5
submodule of the crypto-js
library,
using a / to separate
the name of the main module and the name of the submodule.
Then, write a createGravatarUrl function that
accepts a username, generates an MD5 hash, and returns the URL
for the Gravatar.
import $ from 'jquery'; import md5 from 'crypto-js/md5'; function createGravatarUrl(username) { let userhash = md5(username); return `http://www.gravatar.com/avatar/${userhash.toString()}`; } ...
Take note: In return `http://www.gravatar.com/avatar/${userhash.toString()}`
,
those are not single quote characters. They are backticks,
located just below the Escape key on most US keyboard layouts.
Inside the backticks, you can use the ${userhash.toString()}
syntax to
include JavaScript expression values directly in your string. Here, you refer to the variable
userhash and call its toString method,
but any expression is valid inside of the curly brackets.
Next, use this function to display the Gravatar in new messages.
At the bottom of ChatList’s
drawMessage method (still in dom.js), create a new image
element and set its src
attribute to the
user’s Gravatar.
... $message.append($('<span>', { class: 'message-message', text: m })); let $img = $('<img>', { src: createGravatarUrl(u), title: u }); $messageRow.append($img); $messageRow.append($message); $(this.listId).append($messageRow); $messageRow.get(0).scrollIntoView(); ...
Run your chat app, and you should see a Gravatar pop up this time (Figure 18.4).
Sadly, there is no Gravatar for the wonderwoman
username.
As a result, you get the unexciting default Gravatar.
18.118.2.240