如何检测JavaScript和/或Cookies是否被禁用?

61

如何检测用户的浏览器中是否禁用了JavaScript或Cookies并通知用户?
有什么帮助吗?


19
如果 JavaScript 被禁用,那么运行脚本以检测此情况的是什么? - Ivo Wetzel
5
打开JavaScript的脚本。 - FluffyBeing
9个回答

87

您可以使用以下方法来检查cookie:

function checkCookie(){
    var cookieEnabled = navigator.cookieEnabled;
    if (!cookieEnabled){ 
        document.cookie = "testcookie";
        cookieEnabled = document.cookie.indexOf("testcookie")!=-1;
    }
    return cookieEnabled || showCookieFail();
}

function showCookieFail(){
  // do something here
}


// within a window load,dom ready or something like that place your:
checkCookie();

对于检查 JavaScript,可以使用 <noscript> 标签,并在其中放置一些提示信息。


7
请注意,当 JavaScript 被禁用时,此内容将无法运行 :) - BalusC
13
如果已经写入 testcookie,那么你应该在之后将其删除。 - Vitim.us
3
如果IE的隐私选项设置为“高”,这将无法正常工作。在此模式下,navigator.cookieEnabledtrue,但document.cookie始终为空。最好的方法是删除checkCookie()函数的第一个测试:function checkCookie(){document.cookie="testcookie"; var cookieEnabled=(document.cookie.indexOf("testcookie")!=-1)? true : false; return (cookieEnabled)?true:showCookieFail(); } - Charles
这个检查在Safari 9中失败了。请参见https://github.com/Modernizr/Modernizr/commit/33f00fbbeb12e92bf24711ea386e722cce6f60cc以获取更好的解决方案。 - Noah Solomon
1
无法在IE11中正确检测,您可以在此处进行测试:http://sveinbjorn.org/cookiecheck - Zymotik
显示剩余2条评论

26

更新(2018年6月25日):

很多这样的帖子,包括我的,都是从Modernizr中提取的片段。随着Modernizr代码的更新,它们最终都会过时。

我认为对于这个问题最好的答案应该是直接使用Modernizr。

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

原答案(5/11/17):

这是直接从Modernizr中获取的,并且适用于比本帖其他解决方案更多的浏览器。

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;
}

20

由于 IE 11 中的 cookie 检测无法正常工作,我建议采用 Modernizr 方法:

function areCookiesEnabled() {
    try {
      document.cookie = 'cookietest=1';
      var cookiesEnabled = document.cookie.indexOf('cookietest=') !== -1;
      document.cookie = 'cookietest=1; expires=Thu, 01-Jan-1970 00:00:01 GMT';
      return cookiesEnabled;
    } catch (e) {
      return false;
    }
}

https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cookies.js


2
这比@Noah Solomon的答案更为最新。 - diachedelic
这段代码在Safari 15.2上无法运行,即使阻止了cookies,运行此代码仍会返回true,而不是应该返回的false。@diachedelic,你在Safari上使用什么? - Crashalot
抱歉,我没有解决方案。听起来Safari似乎想要假装它持久保存了cookies,但实际上并没有。 - diachedelic

7
这是最简单的方法。

if (navigator.cookieEnabled) {
  document.write("Cookies Enabled");
} else {
  document.write("Oops Cookies Not Enabled");
}
Check if Cookies Enabled in Your Browser:  
<br />


1
在React应用程序+Firefox中,navigator.cookieEnabled在启动时保持未定义状态,直到某个阶段。如果您需要此标志来确定是否安装redux中间件,则此解决方案无法工作。不确定标志何时被填充。 - Ryuu

4

假设JavaScript已启用,则此代码将告诉您Cookies是否已启用。适用于旧版浏览器。

// returns 1 or 0 instead of true or false. Returns null if inconclusive.
function cookiesEnabled() {
    var i, j, cookies, found;
    if (navigator.cookieEnabled===false) return 0;
    document.cookie = 'testcookiesenabled=1';
    for (i=0; i<2; i++) {
        found = false;
        cookies = document.cookie.split(';');
        j = cookies.length;
        while(j--) {
            while (cookies[j].charAt(0)==' ') {// trim spaces
                cookies[j] = cookies[j].substring(1);
            }
            if (cookies[j].indexOf('testcookiesenabled=')==0) {
                found = true;
                break;
            }
        }
        if (!found) {
            return i;
        }
        // Delete test cookie.
        document.cookie = 'testcookiesenabled=; expires=Thu, 01 Jan 1970 00:00:01 GMT';
    }
    // Results inconclusive.
}

如果只有在JavaScript被禁用时才显示消息,请使用以下代码:

<noscript>JavaScript is disabled. Please enabled JavaScript.</noscript>

3
// Example[1]: if ( hasCookies() )
/**
* @hasCookies:  Check if cookie's are Enabled
* @param  {none} ''
* @return {BOOLEAN} true|false
*/
function hasCookies() {
return (navigator.cookieEnabled);
}

 // Example[2]: if ( JLS.TEST.COOKIE() )
// Java Pattern ( How to write usable JS)
/** @namespace JLS classes and functions. */
var JLS = JLS || {};
/**
* TEST utility
* @namespace JLS
* @class TEST
*/
JLS.TEST = {

/**
* @public-method COOKIE
* @COOKIE  Check if cookie's are Enabled
* @return {BOOLEAN} true|false
*/
 COOKIE: function () {
    //Change this (library). Not main.js (Algorithm)
    return (navigator.cookieEnabled);
    }
};

11
这个回答毫无意义。为什么要使用 if ( hasCookies() ) 而不是 if ( navigator.cookieEnabled )? - besciualex
深度糖衣层 :) - Zeeshan Hassan Memon
没错,这是一些JS 101。所以,我添加了第二个例子(可重用代码)。无论如何都不要考虑客户端cookies;看看“window.localStorage”。 - JimmyLandStudios

0

这个函数可以查看用户的错误信息,还可以停止脚本执行,并返回cookie状态。

function IS_Cookies_Enabled(Show_Message, Stop_Script)
{
    if(Show_Message == undefined){
        Show_Message = true;
    }

    if(Stop_Script == undefined){
        Stop_Script = false;
    }


    var Cookie_Status = navigator.cookieEnabled;
    if (!Cookie_Status)
    { 
        document.cookie = "Test";
        Cookie_Status = document.cookie.indexOf("Test") != -1;
        // Delete test cookies
        document.cookie = "Test=1; expires=Thu, 01-Jan-1970 00:00:01 GMT";

    }

    if((!Cookie_Status) && (Show_Message))
    {
        document.getElementsByTagName('body')[0].innerHTML = "<div style='width: 600px; max-width: 100%; margin: 100px auto;'><h1 style='color: red'>Cookies Required</h1><p style='font-size: 18px;'>Cookies are not enabled on your browser. <br>Please enable cookies in your browser preferences to continue.</p><strong>Sylingo</strong>";
    }

    if((!Cookie_Status) && (Stop_Script))
    {
        throw new Error('Cookies is disabled');
    }
    return Cookie_Status;
}

使用它:

IS_Cookies_Enabled(true, true);  // Will stop script and view error message

IS_Cookies_Enabled(true, false);  // Just view error message

$Cookies_Status = IS_Cookies_Enabled(false, false);  // return cookies status

检查 JavaScript 使用:

<noscript>
Javascript is not enabled on your browser. 
</noscript>

0
这个 JavaScript 函数对我来说一直都很有效:
if (typeof areCookiesAllowed !== 'function') {
  function areCookiesAllowed() {
    var cookies_allowed = navigator.cookieEnabled;

    if (!cookies_allowed) {
      try {
        var cur_dt = new Date();
        var cur_tm = cur_dt.getTime();

        document.cookie = 'cookie_test_' + cur_tm + '=1';
        cookies_allowed = document.cookie.indexOf('cookie_test_' + cur_tm + '=') !== -1;
        document.cookie = 'cookie_test_' + cur_tm + '=1; expires=Thu, 01-Jan-1970 00:00:01 GMT';
      } catch(err) {
        return false;
      };
    };

    return cookies_allowed;
  };
};

if (typeof areCookiesAllowed !== 'function') {
  function areCookiesAllowed() {
    var cookies_allowed = navigator.cookieEnabled;

    if (!cookies_allowed) {
      try {
        var cur_dt = new Date();
        var cur_tm = cur_dt.getTime();

        document.cookie = 'cookie_test_' + cur_tm + '=1';
        cookies_allowed = document.cookie.indexOf('cookie_test_' + cur_tm + '=') !== -1;
        document.cookie = 'cookie_test_' + cur_tm + '=1; expires=Thu, 01-Jan-1970 00:00:01 GMT';
      } catch (err) {
        return false;
      };
    };

    return cookies_allowed;
  };
};

var result_elmt = document.getElementById("result");
var result;

if (areCookiesAllowed() === true) {
  result = 'Congratulations! Cookies are enabled in this Web Browser and on this website!';
} else {
  result = 'Aww Snap! Unfortunatly cookies are NOT enabled in this Web Browser or are disabled on this website.';
};

result_elmt.innerHTML = result;
alert(result);
<span id="result"></span>


-1

尝试使用<noscript>...</noscript>标签来部分地检查JavaScript是否已启用。

<script type="application/javascript">
    document.write("This text would be displayed if JavaScript is enabled");
</script>
<noscript>
    This text would be displayed if JavaScript is not enabled
</noscript>

6
你的例子中的<script>有误。如果启用了JavaScript,则<script>标签内的文本不会被显示为HTML,而是会作为JavaScript程序被执行 - Rory O'Kane

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接