gbCookies

优雅的搜索引擎跳转助手专用COOKIES处理函数

This script should not be not be installed directly. It is a library for other scripts to include with the meta directive // @require https://update.greasyfork.org/scripts/460897/1277476/gbCookies.js

// ==UserScript==
// @name          gbCookies
// @description   cookies tool for SearchEngine Assistant
// @author        F9y4ng
// @version       1.6
// @license       GPL-3.0-only
// ==/UserScript==

(function (global, factory) {
  global = global || self;
  global.gbCookies = factory();
})(typeof window !== "undefined" ? window : this, function () {
  "use strict";
  const gbCookies = {
    getItem: function (sKey) {
      return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + sKey.replace(/[-.+*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
    },
    setItem: function ({ sKey, sValue, sEnd, sPath, sDomain, sSameSite, sSecure }) {
      if (!sKey || /^(?:expires|max-age|path|domain|samesite|secure)$/i.test(sKey)) return false;
      let sExpires = "";
      if (sEnd) {
        switch (sEnd.constructor) {
          case Number:
            sExpires = sEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; expires=" + new Date(Number(new Date()) + sEnd).toUTCString();
            break;
          case String:
            sExpires = "; expires=" + new Date(sEnd);
            break;
          case Date:
            sExpires = "; expires=" + sEnd.toUTCString();
            break;
        }
      }
      document.cookie =
        sKey +
        "=" +
        sValue +
        sExpires +
        (sDomain ? "; domain=" + sDomain : "") +
        (sPath ? "; path=" + sPath : "") +
        (sSameSite ? "; SameSite=" + sSameSite : "") +
        (sSecure ? "; secure" : "");
      return true;
    },
    removeItem: function ({ sKey, sPath, sDomain }) {
      if (!sKey || !this.hasItem(sKey)) return false;
      document.cookie = sKey + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "");
      return true;
    },
    hasItem: function (sKey) {
      return new RegExp("(?:^|;\\s*)" + sKey.replace(/[-.+*]/g, "\\$&") + "\\s*\\=").test(document.cookie);
    },
  };
  return gbCookies;
});