判断当前标签页是否为可视状态
浏览器可以打开很多标签页,下面 👇🏻 的代码段就是判断当前标签页是否是激活的标签页
js
const isBrowserTabInView = () => document.hidden;
isBrowserTabInView();const isBrowserTabInView = () => document.hidden;
isBrowserTabInView();检查当前用户是否支持触摸事件
js
const touchSupported = () => {
('ontouchstart' in window || window.DocumentTouch && document instanceof window.DocumentTouch);
}
console.log(touchSupported());
// Result: 如果支持触摸事件会返回 True 否则返回 Falseconst touchSupported = () => {
('ontouchstart' in window || window.DocumentTouch && document instanceof window.DocumentTouch);
}
console.log(touchSupported());
// Result: 如果支持触摸事件会返回 True 否则返回 False检查当前用户是否是苹果设备
可以使用 navigator.platform 判断当前用户是否是苹果设备
js
const isAppleDevice = /Mac|iPod|iPhone|iPad/.test(navigator.platform);
console.log(isAppleDevice);
// Result: 是苹果设备会返回 Trueconst isAppleDevice = /Mac|iPod|iPhone|iPad/.test(navigator.platform);
console.log(isAppleDevice);
// Result: 是苹果设备会返回 True获得当前使用的浏览器名称
js
function getExplorer() {
const ua = window.navigator.userAgent
const isExplorer = (exp) => {
return ua.indexOf(exp) > -1
}
if (isExplorer('MSIE')) return 'IE'
else if (isExplorer('Firefox')) return 'Firefox'
else if (isExplorer('Chrome')) return 'Chrome'
else if (isExplorer('Opera')) return 'Opera'
else if (isExplorer('Safari')) return 'Safari'
}
const arr = getExplorer()
console.log(arr) //Chromefunction getExplorer() {
const ua = window.navigator.userAgent
const isExplorer = (exp) => {
return ua.indexOf(exp) > -1
}
if (isExplorer('MSIE')) return 'IE'
else if (isExplorer('Firefox')) return 'Firefox'
else if (isExplorer('Chrome')) return 'Chrome'
else if (isExplorer('Opera')) return 'Opera'
else if (isExplorer('Safari')) return 'Safari'
}
const arr = getExplorer()
console.log(arr) //ChromelocalStore常用方法
js
// 存储localStorage
setStore = (params) => {
let name = params.name,
content = params.content,
type = params.type,
datetime = params.datetime
name = `${process.env.VUE_APP_NAME}-${name}`
const obj = {
dataType: typeof content,
content: content,
datetime: new Date().getTime(),
}
if (type) obj.type = type
try {
if (type) {
window.sessionStorage.setItem(name, JSON.stringify(obj))
} else {
// localforage.setItem(name, JSON.stringify(obj))
store.set(name, JSON.stringify(obj))
}
} catch (e) {
console.log(e)
}
}
// 获取localStorage
getStore = (params) => {
let {
name,
type
} = params
let obj = {}
let content
name = `${process.env.VUE_APP_NAME}-${name}`
obj = store.get(name)
if (validatenull(obj)) obj = window.sessionStorage.getItem(name)
if (validatenull(obj)) return obj = obj ? JSON.parse(obj) : {}
if (obj.dataType === 'string') {
content = obj.content
} else if (obj.dataType === 'number') {
content = Number(obj.content)
} else if (obj.dataType === 'boolean') {
content = eval(obj.content)
} else if (obj.dataType === 'object') {
content = obj.content
}
return content
}
// 删除localStorage
removeStore = (name) => {
name = `${process.env.VUE_APP_NAME}-${name}`
store.remove(name)
window.sessionStorage.removeItem(name)
}// 存储localStorage
setStore = (params) => {
let name = params.name,
content = params.content,
type = params.type,
datetime = params.datetime
name = `${process.env.VUE_APP_NAME}-${name}`
const obj = {
dataType: typeof content,
content: content,
datetime: new Date().getTime(),
}
if (type) obj.type = type
try {
if (type) {
window.sessionStorage.setItem(name, JSON.stringify(obj))
} else {
// localforage.setItem(name, JSON.stringify(obj))
store.set(name, JSON.stringify(obj))
}
} catch (e) {
console.log(e)
}
}
// 获取localStorage
getStore = (params) => {
let {
name,
type
} = params
let obj = {}
let content
name = `${process.env.VUE_APP_NAME}-${name}`
obj = store.get(name)
if (validatenull(obj)) obj = window.sessionStorage.getItem(name)
if (validatenull(obj)) return obj = obj ? JSON.parse(obj) : {}
if (obj.dataType === 'string') {
content = obj.content
} else if (obj.dataType === 'number') {
content = Number(obj.content)
} else if (obj.dataType === 'boolean') {
content = eval(obj.content)
} else if (obj.dataType === 'object') {
content = obj.content
}
return content
}
// 删除localStorage
removeStore = (name) => {
name = `${process.env.VUE_APP_NAME}-${name}`
store.remove(name)
window.sessionStorage.removeItem(name)
}复制到剪贴板
js
const copyToClipboard = (text) => navigator.clipboard && navigator.clipboard.writeText && navigator.clipboard.writeText(text)
copyToClipboard("Hello World!")const copyToClipboard = (text) => navigator.clipboard && navigator.clipboard.writeText && navigator.clipboard.writeText(text)
copyToClipboard("Hello World!")检测网站运行在哪种平台设备
使用 navigator.userAgent 来检测网站运行在哪种平台设备上。
js
const detectDeviceType = () =>
/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
navigator.userAgent
) ? "Mobile" : "Desktop";
console.log(detectDeviceType());const detectDeviceType = () =>
/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
navigator.userAgent
) ? "Mobile" : "Desktop";
console.log(detectDeviceType());从URL中获取参数
JavaScript 中有一个 URL 对象,通过它可以非常方便的获取 URL 中的参数。
js
const getParamByUrl = (key) => {
const url = new URL(location.href)
return url.searchParams.get(key)
}const getParamByUrl = (key) => {
const url = new URL(location.href)
return url.searchParams.get(key)
}通过 window.location 或原始 URL 轻松查询 goole.com?search=easy&page=3 的参数。
js
const getParameters = (URL) => {
URL = JSON.parse('{"' + decodeURI(URL.split("?")[1]).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') +'"}');
return JSON.stringify(URL);
};
getParameters(window.location)
// Result: { search : "easy", page : 3 }
/---------------or-------------/
Object.fromEntries(new URLSearchParams(window.location.search))const getParameters = (URL) => {
URL = JSON.parse('{"' + decodeURI(URL.split("?")[1]).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') +'"}');
return JSON.stringify(URL);
};
getParameters(window.location)
// Result: { search : "easy", page : 3 }
/---------------or-------------/
Object.fromEntries(new URLSearchParams(window.location.search))检测当前系统浏览器是否开启暗色主题
js
const isDarkMode = () => window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches;
console.log(isDarkMode())// falseconst isDarkMode = () => window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches;
console.log(isDarkMode())// false获取浏览器 Cookie 的值
js
const cookie = name => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift();
cookie('_ga');
// Result: "GA1.2.1929736587.1601974046"const cookie = name => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift();
cookie('_ga');
// Result: "GA1.2.1929736587.1601974046"清除所有 Cookie
js
const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.\*/, `=;expires=${new Date(0).toUTCString()};path=/`));const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.\*/, `=;expires=${new Date(0).toUTCString()};path=/`));获取用户选定的文本
js
const getSelectedText = () => window.getSelection().toString();
getSelectedText();const getSelectedText = () => window.getSelection().toString();
getSelectedText();
liang14658fox