Using Websnapr in Dynamically Created Web Page Content

If you have the need for creating thumbnail images of website pages, Websnapr is a great web service to use. There are free and premium service levels. The free service is quite liberal in the amount of thumbnails which can be created. Queued requests to create thumbnails are generally processed quickly even with the free service. It’s also easy to use.

As described on their web site, it’s very simple to include access to created thumbnails on a website. The only thing required is to define the location of the websnapr script

<head>
	<script type="text/javascript" src="http://www.websnapr.com/js/websnapr.js"></script>
</head>

and to add the following JavaScript code to the web page location of your choice.

<script type="text/javascript">wsr_snapshot('http://URL', 'websnapr API Key', 'Size');</script>
  • URL is the location you want a thumbnail created for
  • websnapr API Key can be obtained when you register
  • Size defines the size of the thumbnail to create. currently
    • s (202 x 152 pixels)
    • t (90 x 70 pixels)

The image created by websnapr gets loaded to this location in the web page. It works great for web pages which have static content. For example, if the web page always references the same thumbnail and the content including the thumbnail is loaded at the same time the rest of the page is loaded. The first time the thumbnail is requested, the websnapr service queues the web location for thumbnail creation and a temporary image is returned that looks like the following:

ThumbnailQueued

Once the thumbnail image is created, subsequent page loads (or a reload) will return an image of the web page requested.

If thumbnails need to be placed inside dynamically created page content, the standard method to create the thumbnails causes the whole web page to refresh, only loading the thumbnails. The reason for this is the document.write  command in the  websnapr.js script that causes a new page load.

To properly load the thumbnails into dynamically created content on a page, the following javascript can be used:

var urlReferenceString = 'http://webpageToThumbnail';
var thumbnail_div = "#thumbnail_div"; 
var thumbnail = $('<img/>', { 
    src: 'http://images.websnapr.com/?size=s&url=' + urlReferenceString + '&key=' + encodeURIComponent("yourWebsnaprKey") + '&hash=' + encodeURIComponent(websnapr_hash), 
    alt: 'Loading thumbnail...', 
    width: 200, 
    height: 150, 
    id: "thumbnail_img"}); 
$(thumbnail_div).append( 
    '<a href="' + urlReferenceString + '"onmousedown="javascript:this.href=\'http://r.websnapr.com/?r=' +
    encodeURIComponent(uriReferenceString) +
    '\'"target="_blank" rel="nofollow">' + thumbnail[0].outerHTML + '</a>');

This is replicating the websnapr script but without the document.write. JQuery is used in this example to define the <img> element  as a variable and also to append HTML and the img element to the thumbnail_div div element. The websnapr_hash variable is defined in the websnapr script and is constructed using a set of hash values generated by websnapr.  The HTML where the image is to be placed is simply defined by

<div id="thumbnail_div"></div>

This works as long as the websnapr hash values don’t change.  Websnapr does change the values every few minutes and the values are used to correctly validate the registered user key and location of the created thumbnail image. When accessing the thumbnail image URL with expired or incorrect hash values, websnapr returns a image looking like the following:

HashExpired

To correct this, the websnapr.js script must be reloaded and the websnapr_hash variable must be reset. This should be done before loading any image thumbnails into dynamically generated content and each time the content is regenerated to load thumbnail images. Even if the same image is to be loaded. Instead of loading the websnapr script once in the <head> of the document, the following script can be used to load it each time it’s needed:

function load_websnapr_js(callback) { 
    delete websnapr_hash; 
    var script = document.createElement('script'); 
    script.type = 'text/javascript'; 
    script.src = "http://www.websnapr.com/js/websnapr.js?ts=" + new Date().getTime(); 
    script.id = 'websnprJS'; 
    var previousScript = document.getElementById('websnprJS'); 
    if (!!(previousScript)) { 
        document.getElementsByTagName("head")[0].replaceChild(script, previousScript); 
    } else { 
        document.getElementsByTagName("head")[0].appendChild(script); 
    } 

    script.onload = function() { 
        callback(); 
    }; 
}

First, the websnapr_hash variable is deleted, removing the variable all together.  The websnapr script recalculates the value only if the variable does not already exist. The ‘script‘ variable defines the location of the script and tags it with an id. A timestamp is also appended to the src so the browser doesn’t use an already cached version of the websnapr script file. If the websnapr script was already retrieved, it is assigned to the previousScript variable and replaced in the head tag. If it hasn’t been defined, the script is retrieved and appended. Both replacing and appending executes the websnapr script defining the websnapr_hash variable with the current and correct hash value.

Finally, in the function, the callback variable passed in is a function and is executed on the completion of the websnapr script being downloaded and executed. The script included above, that dynamically creates the page content, can be wrapped into a function and passed in as a parameter. it would look like:

load_websnapr_js( 
    function() {
        var urlReferenceString = 'http://webpageToThumbnail';
        var thumbnail_div = "#thumbnail_div"; 
        var thumbnail = $('<img/>', { 
            src: 'http://images.websnapr.com/?size=s&url=' + urlReferenceString + '&key=' + encodeURIComponent("yourWebsnaprKey") + '&hash=' + encodeURIComponent(websnapr_hash), 
            alt: 'Loading thumbnail...', 
            width: 200, 
            height: 150, 
            id: "thumbnail_img"}); 
        $(thumbnail_div).append( 
            '<a href="' + urlReferenceString + '"onmousedown="javascript:this.href=\'http://r.websnapr.com/?r=' +
            encodeURIComponent(uriReferenceString) +
            '\'"target="_blank" rel="nofollow">' + thumbnail[0].outerHTML + '</a>');
    });

It would be nice if the thumbnails could be pre-generated before being loaded into the page with the “thumbnail has been queued” image.  If you know the page URLs in advance (maybe stored in a database), there are a number of ways to make calls to the websnapr web service to generate the images in advance.  Basically your code needs to:

  • retrieve the current version of the websnap.js file with the correct hash values
  • reset the websnapr_hash variable defined in the script
  • call the websnapr web service with the following URL    http://images.websnapr.com/?size=s&url=’ + urlString + ‘&key=’ + encodeURIComponent(“yourWebsnaprKey”) + ‘&hash=’ + encodeURIComponent(websnapr_hash);  for each webpage (urlString) needing a thumbnail image
Advertisements