Skip to content

Instantly share code, notes, and snippets.

@Javison666
Last active September 17, 2020 14:58
Show Gist options
  • Save Javison666/cd29f6c2f3badff7de3ea76c2352480e to your computer and use it in GitHub Desktop.
Save Javison666/cd29f6c2f3badff7de3ea76c2352480e to your computer and use it in GitHub Desktop.
js-browser
export const CookieFn = {
setCookie(cname, cvalue, exdays) {
let d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
let expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
},
getCookie(cname) {
let name = cname + "=";
let ca = document.cookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1);
if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
}
return "";
},
clearCookie(cname) {
this.setCookie(cname, "", -1);
}
}
export const DomFn = {
/**
* 将html字符实体转译成html字符(只适用于浏览器客户端)
* @param {字符实体} str
*/
decodeHtmlEntities(str) {
let t = document.createElement("div");
t.innerHTML = str;
return t.innerText || t.textContent;
},
/**
* 将html字符转译成html字符实体(只适用于浏览器客户端)
* @param {html标签内容} str
*/
encodeHtmlEntities(str) {
let elem = document.createElement('div');
let txt = document.createTextNode(str);
elem.appendChild(txt);
return elem.innerHTML;
},
addListen(dom, event, fn) {
if (dom.addEventListener) { // 所有主流浏览器,除了 IE 8 及更早版本
dom.addEventListener(event, fn);
} else if (dom.attachEvent) { // IE 8 及更早版本
dom.attachEvent(`on${event}`, fn);
}
},
removeEvent(element, type, handler) {
if (element.removeEventListener) {
element.removeEventListener(type, handler, false);
} else if (element.detachEvent) { //detachEvent是ie的事件监听
element.detachEvent('on' + type, handler)
} else {
element['on' + type] = null;
}
},
removeDom(dom) {
if (!dom.remove) {
dom.removeNode(true);
} else {
dom.remove();
}
},
addAnimateClass(dom, animateClass) {
this.toggleClass(dom, animateClass)
this.once(dom, 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', () => {
this.removeClass(dom, animateClass)
})
},
// 摇晃效果
shake(dom) {
this.toggleClass(dom, 'shake animated')
this.once(dom, 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', () => {
this.removeClass(dom, 'shake animated')
})
},
// 一次执行
once(dom, type, callback) {
type = type.split(' ')
for (let item of type) {
let handle = () => {
callback()
dom.removeEventListener(item, handle)
}
dom.addEventListener(item, handle)
}
},
hasClass(dom, cls) {
return dom.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
},
addClass(dom, cls) {
if (!this.hasClass(dom, cls)) dom.className += " " + cls;
},
removeClass(dom, cls) {
if (this.hasClass(dom, cls)) {
var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
dom.className = dom.className.replace(reg, ' ');
}
},
toggleClass(dom, cls) {
if (this.hasClass(dom, cls)) {
this.removeClass(dom, cls);
} else {
this.addClass(dom, cls);
}
}
}
export default DomFn
export const HttpFn = {
httpConnect() {
this.Method = this.Method.toUpperCase();
if (this.Method == 'GET' && this.Args) {
let args = "";
if (typeof this.Args == 'object') {
let arr = new Array();
for (let k in this.Args) {
let v = this.Args[k];
arr.push(k + "=" + v);
}
args = arr.join("&");
} else {
// args = data; //alert("string");
}
this.URL += (this.URL.indexOf('?') == -1 ? '?' : '&') + args;
this.Args = null;
}
// if (this.type !== 'upload') {
if (this.Method == 'POST') {
let args = "";
if (typeof this.Args == 'string') {
args = this.Args;
} else if (typeof this.Args == 'object') {
if (this.dataType == 'json') {
this.Args = JSON.stringify(this.Args)
} else {
let arr = new Array();
for (let k in this.Args) {
let v = this.Args[k];
arr.push(k + "=" + v);
}
args = arr.join("&");
this.Args = encodeURI(args);
}
}
}
// }
let q = this.Request;
let evt1 = this.onSuccess;
let evt2 = this.onFailure;
let evt3 = this.onLoadend;
this.Request.onreadystatechange = () => {
this.onStateChange(q, evt1, evt2, evt3);
};
this.Request.open(this.Method, this.URL, this.Async);
this.setRequestHeader()
try {
this.Request.send(this.Args);
} catch (e) {
console.log("httpconnect exception.");
}
},
setRequestHeader() {
for (let i in this.headers) {
this.Request.setRequestHeader(i, this.headers[i])
}
if (!(this.headers && this.headers['Content-Type'])) {
if (this.dataType == 'json') {
this.Request.setRequestHeader('Content-type', 'application/json;charset=UTF-8');
} else {
this.Request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded;');
}
}
},
onStateChange(xhr, success, failure) {
if (xhr.readyState == 4) {
let s = xhr.status;
if (s == 0) {
console.log("httpconnect to url failure.");
} else if (s >= 200 && s < 400) {
success(xhr);
} else {
failure(xhr);
}
}
},
ajaxFn({
url,
method,
args,
headers,
fn,
dataType,
type
}, callback?) {
this.URL = "";
this.Method = "GET";
this.Async = true;
this.Args = null;
this.headers = headers
this.type = type
this.onSuccess = function () { };
this.onFailure = function () { };
// tslint:disable-next-line
const rq = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
if(typeof callback === 'function'){
callback(rq)
}
this.Request = rq
// 兼容java不接收undefined参数
for (let o in args) {
if (args[o] === undefined) {
args[o] = ''
}
}
let obj = null;
this.URL = url;
this.dataType = dataType;
this.Method = method;
this.Async = true;
this.Args = args;
this.onSuccess = function (xhr) {
let text = xhr.responseText;
if (text.charCodeAt() == 65279) text = text.substring(1); //处理utf8引导字节
eval("obj=" + text);
fn(obj, xhr)
};
this.onFailure = function (xhr) {
eval("obj={Tag:'ERROR',Status:'" + xhr.status + "'}");
fn(obj)
};
this.httpConnect();
},
originHttpPost(obj, fn, callback?) {
const d: any = {
url: obj.url,
method: 'post',
fn,
type: obj.type,
headers: obj.headers,
}
if (obj.json !== undefined) {
d.args = obj.json
d.dataType = 'json'
} else {
d.args = obj.data
}
this.ajaxFn(d, callback)
},
originHttpGet(obj, fn, callback?) {
const d: any = {
url: obj.url,
method: 'get',
headers: obj.headers,
fn,
type: obj.type
}
if (obj.json !== undefined) {
d.args = obj.json
d.dataType = 'json'
} else {
d.args = obj.data
}
this.ajaxFn(d, callback)
},
setRequestTestFn(fn) {
if (this.requestDataAllfn) {
this.requestDataAllfn = fn
}
},
httpPost(obj, callback?) {
return new Promise((resolve) => {
this.originHttpPost(obj, (res) => {
this.setRequestTestFn(res)
resolve(res)
}, callback)
})
},
httpGet(obj, callback?) {
return new Promise((resolve) => {
this.originHttpGet(obj, (res) => {
this.setRequestTestFn(res)
resolve(res)
}, callback)
})
}
}
export default HttpFn
export const LocalStorageFn = {
setStorage(key, value) {
if (this.getStorageType(value) === "Object" || this.getStorageType(value) === "Array") { // 如果是对象
value = JSON.stringify(value);
}
window.localStorage.setItem(key, value);
},
getStorage(key){
let value = window.localStorage.getItem(key);
if(value === null){ // 如果不存在
return false;
}
if(value && value.substring(0,1) === "{" || value.substring(0,1) === "["){ // 如果字符串符合对象或者数组基本特征
value = JSON.parse(value); // 把字符串转为对象
}
return value;
},
removeStorage(key){
this.getStorage(key) && window.localStorage.removeItem(key);
},
clearStorage(){
window.localStorage.clear(); // 清空本地存储
},
getStorageType(object){
/**
* 方法来源:prototype.js
* getStorage(5); // => "Number"
* getStorage({}); // => "Object"
* getStorage(/foo/); // => "RegExp"
* getStorage(''); // => "String"
* getStorage(true); // => "Boolean"
* getStorage([]); // => "Array"
* getStorage(undefined); // => "Window"
* getStorage(Element); // => "Constructor"
**/
return Object.prototype.toString.call(object).match(/^\[object\s(.*)\]$/)[1];
}
}
export default LocalStorageFn
export default () => {
// 重写Websocket方法
let __WebSocket = WebSocket
WebSocket = null
window.WebSocket = new Proxy(__WebSocket, {
construct: function (target, args) {
if (!window.__WsArr__) {
window.__WsArr__ = []
}
const o = new __WebSocket(...args)
o.__send = o.send
o.send = (msg) => {
window.__KsWsSend && window.__KsWsSend(o, msg)
}
o.addEventListener('message', (evt) => {
window.__listenWsMessage && window.__listenWsMessage(o.url, evt)
})
o.addEventListener('close', (evt)=>{
window.__listenWsClose && window.__listenWsClose(o.url, evt)
window.__WsArr__ = window.__WsArr__.filter(i=>i!==o)
})
window.__WsArr__.push(o)
return o
}
})
// 重写ajax方法
let __XMLHttpRequest = XMLHttpRequest
XMLHttpRequest = null
window.XMLHttpRequest = new Proxy(__XMLHttpRequest, {
construct: function (target, args) {
const o = new __XMLHttpRequest(...args)
o.__open = o.open
o.open = null
o.open = (...param) => {
o.__url = param[1]
return o.__open(...param)
}
o.addEventListener('readystatechange', () => {
window.__listenAjax && window.__listenAjax(o.__url, o)
})
return o
}
})
}
export const UrlFn = {
/**
* 跳转链接
* @param {*} href
*/
toHref(href): void {
window.location.href = href
},
/**
* 打开新的标签页
* @param {*} href
*/
toOpen(href): void {
window.open(href)
},
/**
* 解析url参数
* @param {*} url
*/
parseUrl(url) {
let a = document.createElement('a');
a.href = url;
return {
source: url,
protocol: a.protocol.replace(':', ''),
host: a.hostname,
port: a.port,
query: a.search,
file: (a.pathname.match(/\/([^\/?#]+)$/i) || [, ''])[1],
hash: a.hash.replace('#', ''),
path: a.pathname.replace(/^([^\/])/, '/$1'),
relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [, ''])[1],
segments: a.pathname.replace(/^\//, '').split('/'),
params: (function () {
let ret = {};
let seg = a.search.replace(/^\?/, '').split('&').filter(function (v) {
if (v !== '' && v.indexOf('=')) {
return true;
}
});
seg.forEach(function (element) {
let idx = element.indexOf('=');
let key = element.substring(0, idx);
let val = element.substring(idx + 1);
ret[key] = val;
});
return ret;
})()
}
},
urlAddParams(url, params) {
if (typeof (url) == 'undefined' || url == null || url == '') {
return '';
}
if (typeof (params) == 'undefined' || params == null || typeof (params) != 'object') {
return url;
}
url += (url.indexOf("?") != -1) ? "" : "?";
for (const k in params) {
url += ((url.indexOf("=") != -1) ? "&" : "") + k + "=" + encodeURI(params[k]);
}
return url;
},
reportUrl(url): void{
let src = this.urlAddParams(url, obj)
let img = new Image()
img.src = src
}
}
export default UrlFn;
//检测系统
function detectOS(){
let sUserAgent = window.navigator.userAgent;
let isWin = (window.navigator.platform == "Win32") || (window.navigator.platform == "Windows");
let isMac = (window.navigator.platform == "Mac68K") || (window.navigator.platform == "MacPPC") || (navigator.platform == "Macintosh") || (navigator.platform == "MacIntel");
if (isMac) return "Mac";
let isUnix = (window.navigator.platform == "X11") && !isWin && !isMac;
if (isUnix) return "Unix";
let isLinux = (String(window.navigator.platform).indexOf("Linux") > -1);
if (isLinux) return "Linux";
if (isWin) {
let isWin2K = sUserAgent.indexOf("Windows NT 5.0") > -1 || sUserAgent.indexOf("Windows 2000") > -1;
if (isWin2K) return "Win2000";
let isWinXP = sUserAgent.indexOf("Windows NT 5.1") > -1 || sUserAgent.indexOf("Windows XP") > -1;
if (isWinXP) return "WinXP";
let isWin2003 = sUserAgent.indexOf("Windows NT 5.2") > -1 || sUserAgent.indexOf("Windows 2003") > -1;
if (isWin2003) return "Win2003";
let isWinVista= sUserAgent.indexOf("Windows NT 6.0") > -1 || sUserAgent.indexOf("Windows Vista") > -1;
if (isWinVista) return "WinVista";
let isWin7 = sUserAgent.indexOf("Windows NT 6.1") > -1 || sUserAgent.indexOf("Windows 7") > -1;
if (isWin7) return "Win7";
let isWin10 = sUserAgent.indexOf("Windows NT 10") > -1 || sUserAgent.indexOf("Windows 10") > -1;
if (isWin10) return "Win10";
}
return "other";
}
function getDeviceType() {
let UserAgent = window.navigator.userAgent.toLowerCase();
let isChromeOnAndroid=false
if(/android/i.test(UserAgent)){
if (/chrome/i.test(UserAgent)) {
let parts = UserAgent.split('chrome/');
let fullVersionString = parts[1].split(" ")[0];
let versionString = fullVersionString.split('.')[0];
let version = parseInt(versionString);
if (version >= 27) {
isChromeOnAndroid = true;
}
}
}
return {
isMoble: /iphone|ipod|android.*mobile|windows.*phone|blackberry.*mobile/i.test(UserAgent), //判断是否为移动端
isAppleMobile: /iphone|ipod|ipad|Macintosh/i.test(UserAgent), //是否为苹果移动端
isAndroidMobile: /android/i.test(UserAgent), //是否为安卓移动端
isUc: /ucweb/.test(UserAgent), // UC浏览器
isChrome: /chrome/.test(UserAgent.substr(-33, 6)), // Chrome浏览器
isFirefox: /firefox/.test(UserAgent), // 火狐浏览器
isOpera: /opera/.test(UserAgent), // Opera浏览器
isSafire: /safari/.test(UserAgent) && !/chrome/.test(UserAgent), // safire浏览器
is360: /360se/.test(UserAgent), // 360浏览器
isBaidu: /bidubrowser/.test(UserAgent), // 百度浏览器
isSougou: /metasr/.test(UserAgent), // 搜狗浏览器
isIE6: /msie 6.0/.test(UserAgent), // IE6
isIE7: /msie 7.0/.test(UserAgent), // IE7
isIE8: /msie 8.0/.test(UserAgent), // IE8
isIE9: /msie 9.0/.test(UserAgent), // IE9
isIE10: /msie 10.0/.test(UserAgent), // IE10
isIE11: /msie 11.0/.test(UserAgent), // IE11
isLB: /lbbrowser/.test(UserAgent), // 猎豹浏览器
isWX: /micromessenger/.test(UserAgent), // 微信内置浏览器
isQQ: /qqbrowser/.test(UserAgent), // QQ浏览器
isIpad: /ipad/.test(UserAgent), // ipad
isIphone: /iphone os/.test(UserAgent), // iphone
isAndroid: /android/.test(UserAgent), //安卓
isWindowsCe: /windows ce/.test(UserAgent),
isWindowsMobile: /windows mobile/.test(UserAgent),
isWin2K: /windows nt 5.0/.test(UserAgent),
isXP: /windows nt 5.1/.test(UserAgent),
isVista: /windows nt 6.0/.test(UserAgent),
isWin7: /windows nt 6.1/.test(UserAgent),
isWin8: /windows nt 6.2/.test(UserAgent),
isWin81: /windows nt 6.3/.test(UserAgent),
isWin10: /windows nt 10.0/.test(UserAgent),
isChromeOnAndroid
}
},
detectOS(){
let sUserAgent = window.navigator.userAgent;
let isWin = (window.navigator.platform == "Win32") || (window.navigator.platform == "Windows");
let isMac = (window.navigator.platform == "Mac68K") || (window.navigator.platform == "MacPPC") || (navigator.platform == "Macintosh") || (navigator.platform == "MacIntel");
if (isMac) return "Mac";
let isUnix = (window.navigator.platform == "X11") && !isWin && !isMac;
if (isUnix) return "Unix";
let isLinux = (String(window.navigator.platform).indexOf("Linux") > -1);
if (isLinux) return "Linux";
if (isWin) {
let isWin2K = sUserAgent.indexOf("Windows NT 5.0") > -1 || sUserAgent.indexOf("Windows 2000") > -1;
if (isWin2K) return "Win2000";
let isWinXP = sUserAgent.indexOf("Windows NT 5.1") > -1 || sUserAgent.indexOf("Windows XP") > -1;
if (isWinXP) return "WinXP";
let isWin2003 = sUserAgent.indexOf("Windows NT 5.2") > -1 || sUserAgent.indexOf("Windows 2003") > -1;
if (isWin2003) return "Win2003";
let isWinVista= sUserAgent.indexOf("Windows NT 6.0") > -1 || sUserAgent.indexOf("Windows Vista") > -1;
if (isWinVista) return "WinVista";
let isWin7 = sUserAgent.indexOf("Windows NT 6.1") > -1 || sUserAgent.indexOf("Windows 7") > -1;
if (isWin7) return "Win7";
let isWin10 = sUserAgent.indexOf("Windows NT 10") > -1 || sUserAgent.indexOf("Windows 10") > -1;
if (isWin10) return "Win10";
}
return "other";
}
/**
* 返回浏览器版本
*/
function getExplorerInfo() {
let explorer = window.navigator.userAgent.toLowerCase();
// ie
if (explorer.indexOf("msie") >= 0) {
let ver = explorer.match(/msie ([\d.]+)/)[1];
return {
type: "IE",
version: ver
};
}
// firefox
else if (explorer.indexOf("firefox") >= 0) {
let ver = explorer.match(/firefox\/([\d.]+)/)[1];
return {
type: "Firefox",
version: ver
};
}
// Chrome
else if (explorer.indexOf("chrome") >= 0) {
let ver = explorer.match(/chrome\/([\d.]+)/)[1];
return {
type: "Chrome",
version: ver
};
}
// Opera
else if (explorer.indexOf("opera") >= 0) {
let ver = explorer.match(/opera.([\d.]+)/)[1];
return {
type: "Opera",
version: ver
};
}
// Safari
else if (explorer.indexOf("Safari") >= 0) {
let ver = explorer.match(/version\/([\d.]+)/)[1];
return {
type: "Safari",
version: ver
};
}
// 其他
else {
return {
type: '',
version: ''
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment