JavaScript is repeatedly invoking window.location in IE-8

I have implemented a mechanism to track the last visited page using cookies in my JavaScript code, triggered by onload. However, I am facing an issue where the script keeps refreshing repeatedly, almost as if it's triggered by mouse movement even though the only event used is onload.

Below is the snippet of my JavaScript:

<script type='text/javascript'>
    //<![CDATA[
    
    window.onload = function(event){        
        var currentPage = window.location.href;
        var lastVisited = getCookie('udis');
        var sessionId= getCookie('udisSession');
        if(lastVisited === null || lastVisited === undefined){
            setCookie("udis", currentPage, 365);
            lastVisited = getCookie('udis');
        }
        if(sessionId === null || sessionId === undefined){
            setSessionCookie('udisSession');
            if(lastVisited !== currentPage){
                window.location.href = lastVisited;         
            }           
        }
        setCookie("udis", currentPage, 365);
        updateBreadCrumb();
    }
        
        function getCookie(c_name) {
            var i,x,y,ARRcookies=document.cookie.split(";");
            for (i=0;i<ARRcookies.length;i++){
                x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
                y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
                x=x.replace(/^\s+|\s+$/g,"");
                if (x==c_name) {
                    return unescape(y);
                }
            }
        }
        function setSessionCookie(c_name){
        document.cookie=c_name + "=" + 'testSession'+'; expires=; path=/';
    }
        
        function setCookie(c_name,value,exdays){
            var exdate=new Date();
            exdate.setDate(exdate.getDate() + exdays);
            var c_value=escape(value) + ((exdays==null) ? "" : ";   expires="+exdate.toUTCString());
            document.cookie=c_name + "=" + c_value;
        }

    //]]>
    </script>

The scenario works perfectly on Firefox but unfortunately, it causes constant reloading in IE-8.

Answer №1

Make sure to include a space after the semicolon when setting a cookie and always include an expiration date unless you want it to expire when the browser closes.

function setSessionCookie(c_name){
    document.cookie=c_name + "=" + 'testSession'+'; path=/';
}

For more robust cookie handling, consider using the functions available here:

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}

Rather than using setSessionCookie(c_name), consider using

createCookie(c_name, 'testSession');

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using AngularJS ui-router ui-sref results in the error message "Uncaught TypeError: Cannot read property '0' of undefined."

I am currently working on an angularJS component that utilizes ui-router with 2 straightforward route states. export default function Routes($stateProvider, $urlRouterProvider, $locationProvider) { $stateProvider .state('details', { ...

Reactjs - Creating a video component with a placeholder that loads the video seamlessly

I created a Video component that utilizes the React.Suspense component to show a placeholder while the video is loading. However, I'm facing an issue where it seems like the functionality isn't working as intended. When I set the network to "slow ...

transferring data from JavaScript to servlet

For my project, I am working on retrieving contacts from a user's Gmail and Yahoo accounts. I have successfully added checkboxes for the user to select desired email addresses for sending emails. Now, I need to gather all selected email ids and save t ...

"Classes can be successfully imported in a console environment, however, they encounter issues when

Running main.js in the console using node works perfectly fine for me. However, when I attempt to run it through a browser by implementing an HTML file, I do not see anything printed to the console. Interestingly, if I remove any mentions of Vector.ts fro ...

It is necessary for the listener to be a function when handling a socket.io event

I decided to revamp my socket.io server to avoid the notorious "callback hell". Currently, I am exploring the option of listening for an event and passing a function exported by a module as the callback instead of using an anonymous function. My goal is t ...

Determine whether Three.js is compatible

Looking for a way to determine if the browser can handle three.js? I came across using detector.js provided by three.js with this line of code to check if WebGL or canvas is supported: renderer = Detector.webgl ? new THREE.WebGLRenderer() : new THREE.Canv ...

Querying through a database containing 1 million <string Name, int score> pairs efficiently within sub-linear time

My JSON object holds 1 million pairs. var student = {[ { name: "govi", score: "65" }, { name: "dharti", score: "80" }, { name: "Akash", score: "75" },............. up to a million ...

Can IE(7?) cause distortion of backgrounds from sprites?

This task is giving me a headache. We're almost finished with revamping our website. The last step involves consolidating all the glyphs and icons into a sprite. These images are transparent .png files, so we made sure the sprite maintains transparen ...

When utilizing document.addEventListener in JavaScript, Firefox fails to report exceptions triggered by DOMContentLoaded

I'm developing an internal framework that must be independent of any external dependencies such as jQuery. I'm working on implementing a custom DOM ready-style functionality, where callbacks in the ready queue should continue executing even if an ...

What is the best way to fetch data when a single page is in view?

I recently created a jQuery mobile website where I incorporated D3 to visualize some data. The site consists of multiple pages, each defined by <div data-role="page" id="...">...</div>. Given the large amount of data that needs to be loaded f ...

Tips for retrieving a child component's content children in Angular 2

Having an issue with Angular 2. The Main component displays the menu, and it has a child component called Tabs. This Tabs component dynamically adds Tab components when menu items are clicked in the Main component. Using @ContentChildren in the Tabs comp ...

Embedded Javascript fails to function following an async postback triggered by an UpdatePanel

After embedding some JavaScript files in a server control, everything works fine. However, when the server control is placed within an ajax UpdatePanel, it ceases to function after an async postback triggered within the updatepanel. This is the code in th ...

The output from the lodash sortBy function is not aligning with the anticipated result

Sorting this array based on the attributes age and user has become my current challenge. The priority is to first sort by age, followed by sorting by user. In cases where the ages are the same, the sorting should be done based on the user attribute. var us ...

Forgetting your password with React JS

On my login page, there is a button labeled "Forget my password". When I click on this button, I want to be taken directly to the correct page for resetting my password. Currently, when I click on "forget my password", it displays beneath the login sectio ...

Should one be wary of using Javascript setters and getter properties to monitor for modifications?

One interesting feature of Javascript is using Object.create to define setter and getter methods. o = Object.create(Object.prototype, { fooBar: { get: function() { return "Meh" }, set: function(value) { console.log(value) } } }); co ...

Using Javascript to dynamically add an element to an array with a unique index

Given let inputArray = []; $('some_selector').each(function() { let outer, inner; outer=$(this).parent().attr('some_property'); inner=$(this).attr('a_property'); if (!inputArray[outer]) inputArray[outer] = ...

I have found that I can load a CSS file using Node Express, however, it seems to be malfunctioning. On the other hand, some

I have added app.use(express.static(path.join(__dirname, 'public'))); to my app.js file. Now I am using bootstrap.css along with my custom CSS file main.css. index.html: ┊ <meta http-equiv="Content-Type" content="text/html; charset=UTF- ...

Having trouble retrieving JSON data from the open weather API

I'm working on a small website to display the weather of a specific city using an API. However, I am facing an issue where I can't seem to display the temperature from the response. Below are snippets of my JavaScript and HTML files: var ap ...

Tips for refreshing a specific div element at set intervals using JQuery AJAX?

I need to make updates to a specific div element without refreshing the entire HTML page. The code below currently works, but it reloads the entire HTML page. Additionally, I am working with different layouts where I have separate files for the header, l ...

Setting a closure to encapsulate a global variable

I possess a set of functions that allow me to configure prompts for when someone exits a page while inputting values. However, my main concern lies in how to properly encapsulate the checkFlag. Currently, checkFlag is being treated as a global variable whi ...