How to detect that JavaScript and/or Cookies are disabled?

前端 未结 9 1212
鱼传尺愫
鱼传尺愫 2020-11-27 14:13

How to detect that JavaScript or Cookies are disabled in the user\'s browser and notify him any help ?

9条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-27 14:53

    Update (6/25/18):

    A lot of these posts, including mine, are taking snippets from Modernizr. They will all eventually become outdated as the Modernizr code gets updated.

    I think the best answer to this question should be to use Modernizr directly.

    if (Modernizr.cookies) {
      // supported
    } else {
      // not-supported
    }
    

    Original Answer (5/11/17):

    This is taken straight from Modernizr and works in more browsers than other solutions in this post.

    https://github.com/Modernizr/Modernizr/commit/33f00fbbeb12e92bf24711ea386e722cce6f60cc

    function checkCookie(){
        // Quick test if browser has cookieEnabled host property
        if (navigator.cookieEnabled) return true;
        // Create cookie
        document.cookie = "cookietest=1";
        var ret = document.cookie.indexOf("cookietest=") != -1;
        // Delete cookie
        document.cookie = "cookietest=1; expires=Thu, 01-Jan-1970 00:00:01 GMT";
        return ret;
    }
    

提交回复
热议问题