Internet Explorer cookie not being set properly using JavaScript

前端 未结 3 1600
天涯浪人
天涯浪人 2021-01-23 09:16

I am trying to save / restore the scrolling location on Postbacks. My code works for Firefox and all major browsers except for Internet Explorer.

    function sa         


        
3条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-23 09:28

    Apparently Internet Explorer doesn't like the "=" (equal sign) in cookie names that is provided within double quotes. It was interpreting the '='; rather than accepting it as a literal; thus, I solved the problem using the single quotes. Apparently, you have to be forceful with IE! Go figure....

    The following code fixed the problem that I was having -

    function saveScrollPosition() {
    
        // Save the cookie if the requesting browser is Internet Explorer
        if (navigator.appName.indexOf("Microsoft") != -1) {
            // Ensure that the cookie will be saved on IE version 5/+
            if (!document.documentElement.scrollLeft)
              scrollX = document.body.scrollLeft;
            else
              scrollX = document.documentElement.scrollLeft;
            if (!document.documentElement.scrollTop)
              scrollY = document.body.scrollTop;
            else
              scrollY = document.documentElement.scrollTop;
            document.cookie = 'KulScrollPos =' + scrollX+','+scrollY+';'+document.location.pathname;
        }
    
        // Save the cookie for all other major browsers
        else {
            document.cookie = "KulScrollPos="+f_scrollLeft()+","+f_scrollTop()+"; path="+document.location.pathname;
        }
    }
    

    Lessons learned -

    Don't use "=" signs in your cookie names. If you need them, use the single quotes to tell IE not to interpret it, but to accept it as a literal.

提交回复
热议问题