如何检测了cookie浏览器中禁用与AngularJS器中、cookie、AngularJS

2023-09-13 03:41:56 作者:孤雪傲梅

我使用AngularJS在我目前的项目,我想实现一个功能检测如果cookie是在浏览器中禁用。我曾尝试使用AngularJS模块ngCookies来解决这个问题。此功能的主要思想是创造一些饼干,后来检查,如果这个cookie被创建(可用),并显示信息,如果事实并非如此。但它并没有奏效。

I am using AngularJS in my current project and I am trying to implement a feature which detects if cookies are disabled in browser. I have tried to use the AngularJS module "ngCookies" to resolve this issue. The main idea of this feature is to create some cookie, and later check if this cookie was created (and it is available) and show message if it wasn't. But it didn't worked.

控制器:

someProject.controller('CookieCtrl', ['$scope', '$cookieStore', function($scope, $cookieStore) {
    $scope.areCookiesEnabled = false;

    $cookieStore.put("TestCookie", "TestCookieText");
    $scope.cookieValue = $cookieStore.get("TestCookie");

    if ($scope.cookieValue) {
        $cookieStore.remove("TestCookie");
        $scope.areCookiesEnabled = true;
    }
}]);

查看:

<div class="main" data-ng-controller="CookieCtrl">
    <div class="warning_message" data-ng-show="!areCookiesEnabled">
        <span data-ng-bind="areCookiesEnabled"></span>
    </div>
</div>

谁能告诉我哪里是我的错?

Can anybody tell me where is my mistake?

推荐答案

检查:

<div class="warning_message" data-ng-show="!areCookiesEnabled">

数据-NG-秀=!areCookiesEnabled正在评估为。所以,你的消息将在cookie中的情况下,显示不是present。

data-ng-show="!areCookiesEnabled" is evaluating to false. So, your message will not be shown in case of cookies be present.

我做了一个plunker,显示这一点。控制器code是很好,只是从删除NG-展会上看到,或改变!areCookiesEnabled areCookiesEnabled

I've made a plunker that show this. The controller code is fine, just remove ng-show to see, or change from !areCookiesEnabled to areCookiesEnabled.

创建$的CookieStore饼干后,调用该方法$ window.cookies();

After create the cookie with $cookieStore, call the method $window.cookies();

此方法将返回创建的所有Cookie。例如:

This method will return all cookies created. Example:

Object {__utmnodejs: "0x0ceb506e0755ba20", __utma: "137862001.1755124536.1363704654.1383162104.1383305355.73", __utmb: "137862001.2.10.1383305355", __utmc: "137862001", __utmz: "137862001.1383305355.73.49.utmcsr=stackoverflow.co…s-are-disabled-in-browser-with-angularjs/19719108"…}

如果该cookie是禁用,将返回一个空obkect:

If the cookies are disable, will return an empty obkect:

Object {} 

这是发生,因为 $的CookieStore 缓存中的所有创建的cookie,那么,即使它们是unavaliable,你会看到在 $ cookie的缓存值服务。

This is happening because $cookieStore cache all created cookie, so, even they are unavaliable, you will see the cached values in the $cookie service.

http://plnkr.co/edit/TiG6Zx5UKrF8BT9lmdId?p=$p$ PVIEW