Search code examples
javascriptimageonerror

Loading image in the background and testing for onerror event


I have an asp.net webapp which requires user authentication and authentication is set to timeout in 60 minutes. One of the pages in the webapp is a google maps page which loads a kml that has links to information located on the secure site. I am attempting to resolve the issue of mobile users who might let their session expire and return to their browser which is still on the Google Maps page and although the map still works, all links to the information on the secure site will result in a redirect to login.aspx. The solution I've been trying to implement is to load a very small image file in the background on a set interval and to perform redirect when onerror event occurs. My test code is as follows:

<script type="text/javascript">
    var interval;
    interval = setInterval('chkAuth()', 10000);

    function chkAuth() {
        var testImg = new Image();
        testImg.onerror = function () {
            alert("Your session has expired!");
        }
        testImg.onload = function () {
            alert("Your session has extended!");
        }
        testImg.src = "image url"
    }
</script>

When I test the code I get the onload event even if my session has expired which I can verify by trying to load the image in another window which results in a redirect to login.aspx. I have tried testing the onerror event by putting an incorrect url as the image source and it does trigger in that case. My thinking is that this solution would also have the effect of extending my asp.net session at least while the browser is active.

Why am I not getting an onerror event when the image url results in a redirect to login.aspx?


Solution

  • Solved it like this:

    function chkAuth() {
            var date = new Date();
            var currentTime = date.getTime();
            var imgURL = 'small.png' + '?time=' + currentTime;
            var testImg = new Image();
            testImg.onerror = function () {
                alert("Your session has expired!");
                location.reload();
            }
            testImg.onload = function () {
                alert("Your session has extended!");
            }
            testImg.src = imgURL;
        }
    

    The problem was the image object was being stored in the browser cache. By adding the current time to the URL string I am forcing the browser to reload the image. It didn't occur to me that the image would be cached since I was only loading the image object in the background without binding it to the document.