【问题标题】:Check if cookie exist in a javascript检查 cookie 是否存在于 javascript 中
【发布时间】:2017-11-09 23:02:50
【问题描述】:

我的 rails app 上有以下 JavaScript,我只想在 cookie 不存在时运行它。

function getGeoLocation() {
    navigator.geolocation.getCurrentPosition(setGeoCookie);
}

function setGeoCookie(position) {
    var cookie_val = position.coords.latitude + "|" + position.coords.longitude;
    document.cookie = "lat_lng=" + escape(cookie_val);
}

我正在使用它来调用我的 rails 应用程序上的脚本:

 <%- unless @lat_lng %>
        <script>
            getGeoLocation();
        </script>
  <%- end %>

更新

我根据@Njdhv 的回答更新了我的application.js 文件,但弹出窗口仍然出现。这是我所做的:

function getCookieByName(name) {
var parts = document.cookie.split('; '),
    len = parts.length,
    item, i, ret;
for (i = 0; i < len; ++i) {
    item = parts[i].split('=');
    if (item[0] === name) {
        ret = item[1];
        return ret ? unescape(ret) : '';
    }
    }
 return null;
}

if(getCookieByName('lat_lng') != null){
    console.log('lat_lng')
    function getGeoLocation() {
        navigator.geolocation.getCurrentPosition(setGeoCookie);
    }

    function setGeoCookie(position) {
        var cookie_val = position.coords.latitude + "|" + position.coords.longitude;
       document.cookie = "lat_lng=" + escape(cookie_val);
    }
}else{
//you can put your logic here...
}

【问题讨论】:

标签: javascript ruby-on-rails cookies


【解决方案1】:

我发现了问题所在,我必须在我的视图中更改它:

从此:

 <%- unless @lat_lng %>
    <script>
        getGeoLocation();
    </script>
<%- end %>

到这里:

<% if cookies[:lat_lng].nil? %>
    <script>
        getGeoLocation();
    </script>
<% end %>

【讨论】:

    【解决方案2】:

    当您保存了多个 cookie 时,您的搜索 cookie 可能不是 cookie 数组中的第一个 ccokie,您必须同时搜索“lat_lng”和“lat_lng”。

        var lat_lng;
    
            if (navigator.cookieEnabled) {
              cookieArray = document.cookie.split(";");
              cookieArray.forEach(myFunction);
    
              console.log(cookieArray)
    
              function myFunction(item, index) {
                if (item.split("=")[0] == " lat_lng" || item.split("=")[0] == "lat_lng") {
                  lat_lng = item.split("=")[1];
                  console.log("lat_lng " + lat_lng)
                }
              }
            }
    
    if(lat_lng == null){
    
      //what you want to happen
    
    }
    

    【讨论】:

    • 感谢@Nisal Edu 的回复...我在if(lat_lng == null){ 之后添加了我的代码,并且弹出窗口仍然出现。我忘了提到我在 Rails 应用程序中使用它。如果有帮助,我还用更多信息更新了我的问题。
    【解决方案3】:

    您可以使用从当前位置访问的document.cookie 读取所有 cookie。

    根据您的要求,在您的application 中需要readwrite cookie,这样您就可以为cockie getsetclear(删除)创建自己的Singleton

    单例模式将特定对象的实例数限制为一个。这个单一实例称为单例。

    下面我创建了一个Singleton,名字是cookieUtility

    var cookieUtility = (function() {
        return {
            /**
             * Creates a cookie with the specified name and value. Additional settings for the cookie may be optionally specified
             * (for example: expiration, access restriction, SSL).
             * @param {String} name The name of the cookie to set.
             * @param {Object} value The value to set for the cookie.
             * @param {Object} [expires] Specify an expiration date the cookie is to persist until. Note that the specified Date
             * object will be converted to Greenwich Mean Time (GMT).
             * @param {String} [path] Setting a path on the cookie restricts access to pages that match that path. Defaults to all
             * pages ('/').
             * @param {String} [domain] Setting a domain restricts access to pages on a given domain (typically used to allow
             * cookie access across subdomains). For example, "sencha.com" will create a cookie that can be accessed from any
             * subdomain of sencha.com, including www.sencha.com, support.sencha.com, etc.
             * @param {Boolean} [secure] Specify true to indicate that the cookie should only be accessible via SSL on a page
             * using the HTTPS protocol. Defaults to false. Note that this will only work if the page calling this code uses the
             * HTTPS protocol, otherwise the cookie will be created with default options.
             */
            set: function(name, value) {
                var argv = arguments,
                    argc = arguments.length,
                    expires = (argc > 2) ? argv[2] : null,
                    path = (argc > 3) ? argv[3] : '/',
                    domain = (argc > 4) ? argv[4] : null,
                    secure = (argc > 5) ? argv[5] : false;
                document.cookie = name + "=" + escape(value) + ((expires === null) ? "" : ("; expires=" + expires.toUTCString())) + ((path === null) ? "" : ("; path=" + path)) + ((domain === null) ? "" : ("; domain=" + domain)) + ((secure === true) ? "; secure" : "");
            },
            /**
             * Retrieves cookies that are accessible by the current page. If a cookie does not exist, `get()` returns null. The
             * following example retrieves the cookie called "valid" and stores the String value in the variable validStatus.
             *
             *
             * @param {String} name The name of the cookie to get
             * @return {Object} Returns the cookie value for the specified name;
             * null if the cookie name does not exist.
             */
            get: function(name) {
                var parts = document.cookie.split('; '),
                    len = parts.length,
                    item, i, ret;
                // In modern browsers, a cookie with an empty string will be stored:
                // MyName=
                // In older versions of IE, it will be stored as:
                // MyName
                // So here we iterate over all the parts in an attempt to match the key.
                for (i = 0; i < len; ++i) {
                    item = parts[i].split('=');
                    if (item[0] === name) {
                        ret = item[1];
                        return ret ? unescape(ret) : '';
                    }
                }
                return null;
            },
            /**
             * Removes a cookie with the provided name from the browser
             * if found by setting its expiration date to sometime in the past.
             * @param {String} name The name of the cookie to remove
             * @param {String} [path] The path for the cookie.
             * This must be included if you included a path while setting the cookie.
             */
            clear: function(name, path) {
                if (this.get(name)) {
                    path = path || '/';
                    document.cookie = name + '=' + '; expires=Thu, 01-Jan-1970 00:00:01 GMT; path=' + path;
                }
            }
        }
    })();
    

    怎么用?

    1) 用于获取 cookie

    cookieUtility.get('name')//need to pass cookie name
    

    2)用于设置cookie

    cookieUtility.set('name','value')//need to pass cookie name and value of cookie 
    

    3) 用于删除 cookie

    cookieUtility.clear('name') //need to pass cookie name and path(if required)
    

    【讨论】:

    • 感谢@Njdhv 的回复,请检查我的问题以了解我所做的更新..
    • @Theopap 请检查我用Singleton 更新的答案。正如我在你的问题中看到的那样,你也想write cookie 所以我希望这会对你有很大帮助。
    【解决方案4】:

    javascript 的文档很好地解释了这一点。

    使用document.cookie,您可以检查 cookie 是否存在。 只需将其与 if 语句结合起来,看起来就像这样:

    if (document.cookie == null) {
    // do nothing
    }
    else {
    // run it!
    }
    

    【讨论】:

    • 如果这不是您要寻找的答案,您能否更清楚地说明您的实际问题是什么?
    • 感谢@John 的回复...我已经用更多信息更新了这个问题。如果 cookie 已经存在,我不希望出现地理位置弹出窗口。
    猜你喜欢
    • 2012-03-10
    • 2012-10-15
    • 2012-05-17
    • 2017-10-19
    • 2014-10-15
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多