How do I programmatically refresh a browser

hpekristiansen picture hpekristiansen · Nov 14, 2012 · Viewed 42.6k times · Source

I have three computers; Server, Client and Viewer. I am in control of the server and the viewer. workflow

  1. The user on the Client connects to the Server and is presented with a webpage.
  2. Through a php script the user uploads an image.
  3. The image is imbedded in some html.
  4. The Viewer is a computer totally without user interaction - there is no keyboard. The Viewer is always at all time running a web browser, displaying the picture page.

My problem now is that even though the picture changes on the server disk, the webpage is not updated. How do I refresh the web browser on the viewer, or part of the webpage?

I know html, css, javascript, php and ajax, but apparently not well enough.

Answer

pete picture pete · Jan 12, 2013

There are at least three ways to accomplish this.

Pure HTML

As pointed out by Amitd's comment, in "show.html" add the following <meta> tag to your document's <head> element:

<meta http-equiv="refresh" content="5" />

This will automatically refresh the page every 5 seconds. Adjust the value of the content attribute to the desired number of seconds.

Pure JavaScript:

As pointed out by MeNoMore, document.location.reload() will refresh the page when you call it.

<script type="text/javascript">
    //put this somewhere in "show.html"
    //using window onload event to run function
    //so function runs after all content has been loaded.
    //After refresh this entire script will run again.
    window.onload = function () {
        'use strict';
        var millisecondsBeforeRefresh = 5000; //Adjust time here
        window.setTimeout(function () {
            //refresh the entire document
            document.location.reload();
        }, millisecondsBeforeRefresh);
    };
</script>

And as pointed out by tpower AJAX requests could be used, but you'd need to write a web service to return a url to the desired image. The JavaScript to do an AJAX request would look something like this:

<script type="text/javascript">
    //put this somewhere in "show.html"
    //using window onload event to run function
    //so function runs after all content has been loaded.
    window.onload = function () {
        'use strict';
        var xhr,
            millisecondsBeforeNewImg = 5000;    // Adjust time here
        if (window.XMLHttpRequest) {
            // Mozilla, Safari, ...
            xhr = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
            // IE
            try {
                // try the newer ActiveXObject
                xhr = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    // newer failed, try the older one
                    xhr = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {
                    // log error to browser console
                    console.log(e);
                }
            }
        }
        if (!xhr) {
            // log error to browser console
            console.log('Giving up :( Cannot create an XMLHTTP instance');
        }
        xhr.onreadystatechange = function () {
            var img;
            // process the server response
            if (xhr.readyState === 4) {
                // everything is good, the response is received
                if (xhr.status === 200) {
                    // perfect!
                    // assuming the responseText contains the new url to the image...
                    // get the img
                    img = document.getElementById('theImgId');
                    //set the new src
                    img.src = xhr.responseText;
                } else {
                    // there was a problem with the request,
                    // for example the response may contain a 404 (Not Found)
                    // or 500 (Internal Server Error) response code
                    console.log(xhr.status);
                }
            } else {
                // still not ready
                // could do something here, but it's not necessary
                // included strictly for example purposes
            }
        };
        // Using setInterval to run every X milliseconds
        window.setInterval(function () {
            xhr.open('GET', 'http://www.myDomain.com/someServiceToReturnURLtoDesiredImage', true);
            xhr.send(null);
        }, millisecondsBeforeNewImg)
    };
</script>

Other methods:

Finally, to answer your question to tpower's answer... $.ajax() is using jQuery to do the AJAX call. jQuery is a JavaScript library that makes AJAX calls and DOM manipulation a lot simpler. To use the jQuery library, you'd need to include a reference to it in your <head> element (version 1.4.2 used as an example):

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

You could also download the "jquery.min.js" and host it locally instead but that would, of course, only change the url you are loaded the script from.

The AJAX function above, when written using jQuery would look more like this:

<script type="text/javascript">
    //put this somewhere in "show.html"
    //document.ready takes the place of window.onload
    $(document).ready(function () {
        'use strict';
        var millisecondsBeforeNewImg = 5000;    // Adjust time here
        window.setInterval(function () {
            $.ajax({
                "url": "http://www.myDomain.com/someServiceToReturnURLtoDesiredImage",
                "error": function (jqXHR, textStatus, errorThrown) {
                    // log error to browser console
                    console.log(textStatus + ': ' + errorThrown);
                },
                "success": function (data, textStatus, jqXHR) {
                    //get the img and assign the new src
                    $('#theImgId').attr('src', data);
                }
            });
        }, millisecondsBeforeNewImg);
    });
</script>

As I hope is evident, the jQuery version is much simpler and cleaner. However, given the small scope of your project I don't know if you'd want to bother with the added overhead of jQuery (not that it's all that much). Neither do I know if your project requirements allow the possibility of jQuery. I included this example simply to answer your question of what $.ajax() was.

I'm equally sure that there are other methods by which you can accomplish refreshing the image. Personally, if the image url is always changing, I'd use the AJAX route. If the image url is static, I'd probably use the <meta> refresh tag.