Is it possible to check if cookies are enabled with modernizr?

后端 未结 4 1910
北荒
北荒 2021-01-12 07:48

I was researching about how to check if the cookies are enabled in a browser and i found a lot of answer, i even tested a few ones, but after that a friend of mine

相关标签:
4条回答
  • 2021-01-12 08:05

    Below code is copied from http://sveinbjorn.org/cookiecheck.

    function are_cookies_enabled()
    {
        var cookieEnabled = (navigator.cookieEnabled) ? true : false;
    
        if (typeof navigator.cookieEnabled == "undefined" && !cookieEnabled)
        { 
            document.cookie="testcookie";
            cookieEnabled = (document.cookie.indexOf("testcookie") != -1) ? true : false;
        }
        return (cookieEnabled);
    }
    
    0 讨论(0)
  • 2021-01-12 08:06

    check this url, hope it's helpful :

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

    0 讨论(0)
  • 2021-01-12 08:11

    Another way with PHP

    HTML/PHP:

    <?php
      session_start();
      $_SESSION['cook'] = 1;
      echo "<img src=\"cookcheck.php\">";
    ?>
    

    PHP - cookcheck.php:

     <?php
         session_start();
    
         if ($_SESSION['cook'] !== 1) 
                                 { $image="/nocookmsg.png"; }    # Cookies NOT Enabled
                                   else { $image="/blank.png"; } # Cookies Enabled
    
         $img=imageCreateFromPNG($image);   # Create Image
         header("Content-type: image/png"); # Send Header
         imagePNG($image);                  # Send Image
     ?>
    
    0 讨论(0)
  • 2021-01-12 08:21

    A direct answer to the question is 'Yes!' and it is built in

    Example code:

    if (Modernizr.cookies == false) {
    
        alert('Please enable cookies');    
    }
    else { 
        // do something with cookies
    }
    

    You can also use the css class .cookies or .no-cookies to show/hide a panel telling the user they need cookies enabled.

    .cookies #noCookies
    {
        display: none;
    }
    
    <div id='#noCookies'>
       This site requires cookies! Please turn them on already!
    </div>
    

    (This .cookies class is added to <body> tag by Modernizr).

    Note: If you are creating a custom build of Modernizr the cookies option is currently 'hidden' under the 'Non-core detects' section.

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