javascript 工具方法

  • 数量 50 个左右
  • 大小 4kb 左右
  • 如果超过了会删除,有的是随机,有的根据时间删除
  • 服务器可以设置,客户端也可以设置
  • set-cookie 服务器设置
  • document.cookie 可读可写属性
  • cookie 每次只能设置一个
  • document.cookie="name=1" 必须是 http 协议才工作,只能设置一次 cookie
  • document.cookie="name=1; age=2" 必须是 http 协议才工作 分号加空格,这样设置 age 没生效 name 生效了
  • name cookie 的名字唯一
  • value cookie 的值 字符串
  • domain 设置 cookie 在哪个域下是有效的
  • path cookie 的路径,只能在规定的 url 下使用 cookie
  • document.cookie="color=red; domain=127.0.0.1; path=/docs" 这条代码执行后只有在 127.0.0.1 下的/docs 目录下才有,并且跟上面执行的同时执行是生效的
  • expires cookie 的过期时间 默认 Session 会话期的一个值,浏览器关闭就删除了,日期格式必须是 GMT
  • GMT 是格林标准时间 console.log(new Date());
  • document.cookie="margin=20; expires=" + new Date(2008,1,1); 设置 2008 年 2 月 1 号为过期时间,直接就设置立马又被删除
  • max-age cokie 的有效期这个是 http1.1 的内容,expires 是具体到某一个时间点
  • max-age 是某一个时间段,比如给一个 300 就是 300 秒
  • max-age = -1 是一个临时的 cookie 不会生成
  • max-age = 0 有效期到了马上失效
  • max-age = 正数
  • document.cookie = 'padding=30; max-age=1' 1 秒立马消失
  • HttpOnly 有这个标记的 cookie 前端无法获取,只能后端操作
  • Secure 设置 cookie 只能通过 https 协议传输,主要是为了安全
  • SameSite 设置这个 cookie 在跨域请求的时候不能被发送,默认为 None(跨域时不会传输)
ajax("js/data.json", function (data) {
  console.log(data);
});
import { Milliseconds } from "@/enums/millisecondsEnum";
import { isDate, isString, isObject } from "./is";

function encode(v: string) {
  return encodeURIComponent(v);
}

function decode(v: string) {
  return decodeURIComponent(v);
}

function stringifyValue(v: unknown): string {
  return encode(isObject(v) ? JSON.stringify(v) : "" + v);
}

function getExpiresString(offsetMilliseconds: number) {
  const now = new Date();
  now.setMilliseconds(now.getMilliseconds() + offsetMilliseconds);
  return now.toUTCString();
}

function parseExpiresOptionString(str: string) {
  if (str.trim() === "") {
    return void 0;
  }
  const days = str.match(/(\d+)d/);
  const hours = str.match(/(\d+)h/);
  const minutes = str.match(/(\d+)m/);
  const seconds = str.match(/(\d+)s/);

  let milliseconds = 0;

  if (days) {
    milliseconds = +days[1] * Milliseconds.IN_DAY;
  }

  if (hours) {
    milliseconds += +hours[1] * Milliseconds.IN_HOUR;
  }

  if (minutes) {
    milliseconds += +minutes[1] * Milliseconds.IN_MINUTE;
  }

  if (seconds) {
    milliseconds += +seconds[1] * 1000;
  }
  return (milliseconds && getExpiresString(milliseconds)) || void 0;
}

function parseResult(v: string) {
  let res;
  try {
    res = JSON.parse(decode(v));
  } catch (e) {
    return v;
  }
  return res;
}

/**
 * 设置cookie
 * @param key key name
 * @param val value
 * @param opts extra options
 * @returns
 */
export function setCookie(key: string, val: any, opts: CookieOpts = {}) {
  key = key.trim();
  if (key === "") {
    return false;
  }

  let expires;
  if (opts.expires) {
    if (isDate(opts.expires)) {
      expires = opts.expires.toUTCString();
    } else if (isString(opts.expires)) {
      expires = parseExpiresOptionString(opts.expires);
    } else {
      expires = Number.isNaN(opts.expires) ? 0 : opts.expires;
      expires =
        (expires && getExpiresString(expires * Milliseconds.IN_DAY)) || void 0;
    }
  }

  const keyValue = `${encode(key)}=${stringifyValue(val)}`;
  const cookieData = [
    keyValue,
    (expires && `expires=${expires}`) || "",
    (opts.path && `path=${opts.path}`) || "",
    (opts.domain && `domain=${opts.domain}`) || "",
    (opts.samesite && `SameSite=${opts.samesite}`) || "",
    (opts.secure && "Secure") || "",
  ];

  document.cookie = cookieData.join(";");
  return true;
}

/**
 * 获取Cookie值
 * @param key cookie键名
 */
export function getCookie(key: string) {
  if (key.trim() === "") {
    return null;
  }

  key = encode(key);
  const matches = document.cookie.match(
    new RegExp(`(?:^|;+|\\s+)${key}=([^;]*)`)
  );
  let res = matches && matches[1];

  if (res) {
    res = parseResult(res);
  }
  return res;
}

/**
 * 获取所有cookie
 */
export function getAllCookie(): Recordable {
  const docCookies = document.cookie;
  const cookies = docCookies ? docCookies.split(";") : [];
  const result: Recordable = {};

  for (const item of cookies) {
    const [k, v] = item.split("=");
    result[decode(k)] = v && parseResult(v);
  }

  return result;
}

/**
 * 判断cookie是否存在
 * @param key cookie键名
 */
export function hasCookie(key: string) {
  return getCookie(key) !== null;
}

/**
 * 删除cookie
 * @param key
 */
export function removeCookie(key: string) {
  if (key.trim() === "") {
    return;
  }

  setCookie(key, "", { expires: -1 });
}

export default {
  get: (key: string) => getCookie(key),
  set: (key: string, val: any, opts: CookieOpts = {}) =>
    setCookie(key, val, opts),
  getAll: () => getAllCookie(),
  has: (key: string) => hasCookie(key),
  remove: (key: string) => removeCookie(key),
};

复制内容到剪贴板

/**
 * 复制文本回退方案,在不支持navigator.clipboard的情况下
 * @param text
 */
export function copy2ClipboardFallbackUsingRange(text: string) {
  const spanNode = document.createElement('span')
  spanNode.textContent = text

  spanNode.style.position = 'fixed'
  spanNode.style.left = '0'
  spanNode.style.top = '0'
  document.body.appendChild(spanNode)

  const range = document.createRange()
  range.selectNodeContents(spanNode)

  const ws = window.getSelection()
  ws?.removeAllRanges()
  ws?.addRange(range)

  let isSuccessed: boolean
  try {
    isSuccessed = document.execCommand('copy')
  } catch (e: any) {
    isSuccessed = false
  }

  ws?.removeAllRanges()
  spanNode.remove()

  return isSuccessed
}

export function copy2ClipboardFallbackUsingDOM(text: string) {
  const textarea = document.createElement('textarea')
  textarea.value = text

  textarea.contentEditable = 'true'
  textarea.style.position = 'fixed'
  textarea.style.left = '0'
  textarea.style.top = '0'
  document.body.appendChild(textarea)

  textarea.focus()
  textarea.select()

  let isSuccessed: boolean
  try {
    isSuccessed = document.execCommand('copy')
  } catch (e: any) {
    isSuccessed = false
  }

  textarea.remove()
  return isSuccessed
}

/**
 * 复制文本到粘贴板
 * @param text
 * @returns
 */
export default function (text: string): Promise<void> {
  return new Promise((resolve, reject) => {
    if (navigator.clipboard) {
      navigator.clipboard.writeText(text).then(resolve, reject)
    } else {
      copy2ClipboardFallbackUsingRange(text) ? resolve() : reject()
    }
  })
}

var manageCookie = {
  set: function (name, value, day) {},
  remove: function () {},
  get: function () {},
};

鼠标点击移动

var drag = {
  init: function (dom) {
    this.dom = dom;
    this.bindEvent();
  },
  bindEvent: function () {
    this.dom.onmousedown = this.mouseDown.bind(this);
  },
  mouseDown: function (e) {
    document.onmousemove = this.mouseMove.bind(this);
    document.onmouseup = this.mouseUp.bind(this);
    this.disX = e.clientX - this.dom.offsetLeft;
    this.disY = e.clientY - this.dom.offsetTop;
  },
  mouseMove: function (e) {
    this.newLeft = e.clientX - this.disX;
    this.newTop = e.clientY - this.disY;
    this.dom.style.left = this.newLeft + "px";
    this.dom.style.top = this.newTop + "px";
  },
  mouseUp: function () {
    document.onmousemove = null;
    document.onmouseup = null;
  },
};
drag.init(document.getElementById("box"));

localstorage web Storage

  • 大小 5mb
  • sessionStorage 会话级别的存储,存储的数据在本次会话有用,会话结束后失效,数据只在当前窗口有效,
  • localstorage 在整个域名下所有都有效
  • 都继承 Storage console.dir(Storage);

属性方法

  • length 本地存储数据的数量
  • key() 通过索引找到存储的数据(比较鸡肋)
  • getItem() 通过键名取到本地存储的数据
  • setItem() 设置
  • removeItem() 删除一个本地存储数据
  • clear(); 清空本地存储的数据
  • 当 localstorage 变化就能监听,是跨页面的,
  • 无痕模式下 localstorage 会清除本地存储 (待验证)
window.addEventListener("storage", function (ev) {
  console.log(ev.key); //修改的是哪个localstorage的名字
  console.log(ev.newValue); //修改后的数据
  console.log(ev.oldValue); //修改前的数据
  console.log(ev.storageArea); //修改的storage对象(storage所有数据)
  console.log(ev.url); //返回操作的哪个页面的url
});

插件 console Importer

$i('jquery')

Last Updated:
Contributors: 刘荣杰