Internet Explorer cookie not being set properly using JavaScript

前端 未结 3 1557
天涯浪人
天涯浪人 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.

    0 讨论(0)
  • 2021-01-23 09:29

    Cookie data is not supposed to be able to contain commas. You'll need to encode or escape your scroll data before writing it, and then decode or unescape it on read.

    Edit: You could also just change your delimiter; maybe try a pipe ( | )?

    0 讨论(0)
  • 2021-01-23 09:55

    Comma is valid separator for multiple cookies. Try replace comma to %2C, or escape() whole cookie value.

    0 讨论(0)
提交回复
热议问题