在其子域上为外部网站创建和删除Cookie

时间:2016-10-14 18:53:46

标签: javascript jquery cookies setcookie

在Jquery中设置Cookie功能

function setCookie(cookieName, cookieValue, cookieExpireDays) {
        var d = new Date();
        d.setTime(d.getTime() + (cookieExpireDays * 24 * 60 * 60 * 1000));
        var expires = "expires=" + d.toUTCString();
        document.cookie = cookieName + "=" + cookieValue + ";" + expires + ";" + "path=/";
    }

在Jquery中删除函数

function deleteCookie(name) {
    var domain = location.hostname,
        path = '/'; // root path

    document.cookie = [
        name, '=',
        '; expires=' + new Date(0).toUTCString(),
        '; path=' + path,
        '; domain=' + domain
    ].join('');
}

这适用于本地链接,但是当我尝试在外部网站上使用它时。我可以获取我的document.cookie但deleteCookie函数不会删除cookie。有什么想法吗?

*请记住,我只是从Google Chrome控制台运行这些脚本

3 个答案:

答案 0 :(得分:1)

我可能会误解你问题中的某些内容,但这是我处理获取,设置和删除我设置的cookie的方式。

小提琴:https://jsfiddle.net/hmvyu3L6/

<button class='set'>set</button>
<button class='get'>get</button>
<button class='delete'>delete</button>

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    var expires = 'expires=' + d.toUTCString();
    document.cookie = cname + '=' + cvalue + '; ' + expires;
  }

  function getCookie(cname) {
    var name = cname + '=',
    ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
      var c = ca[i];
      while (c.charAt(0) == ' ') {
        c = c.substring(1);
      }
      if (c.indexOf(name) == 0) {
        return c.substring(name.length,c.length);
      }
    }
    return '';
  }

  function deleteCookie( name ) {
    document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
  }

  var value = 'hey there';

  $('.set').on('click', function() {
    setCookie('testCookie', value, 360);
  });

  $('.get').on('click', function() {
    console.log(getCookie('testCookie'));
  });

  $('.delete').on('click', function() {
    deleteCookie('testCookie');
  });

答案 1 :(得分:0)

如果Cookie是HttpOnly,您将无法使用javascript或jquery删除它们。

确保您的域名和路径完全匹配。如果它们不同(例如.subdomain.domain.com而不是.domain.com,或/path而不是/),则脚本不会影响Cookie。

答案 2 :(得分:0)

好吧,我正在回答我自己的问题,因为我改变了一些事情并且现在有效。

    var domain = location.hostname

    function setCookie(cookiename, cookievalue, expiredays, domain) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            var expires = "; expiredays=" + date.toGMTString();   
            document.cookie = cookiename+ "=" + cookievalue+ expires + "; domain=" + domain + "; path=/";
    }

function deleteCookie(cookiename, domain) {
    setCookie(cookiename, "", -1, domain);
}

deleteCookie("Cookie_Name",domain)