Appearance
1、直接下载文件
js
const downloadFile = (api, params, fileName, type = 'get') => {
axios({
method: type,
url: api,
responseType: 'blob',
params: params
}).then((res) => {
let str = res.headers['content-disposition']
if (!res || !str) {
return
}
let suffix = ''
// 截取文件名和文件类型
if (str.lastIndexOf('.')) {
fileName ? '' : fileName = decodeURI(str.substring(str.indexOf('=') + 1, str.lastIndexOf('.')))
suffix = str.substring(str.lastIndexOf('.'), str.length)
}
// 如果支持微软的文件下载方式(ie10+浏览器)\
if (window.navigator.msSaveBlob) {
try {
const blobObject = new Blob([res.data]);
window.navigator.msSaveBlob(blobObject, fileName + suffix);
} catch (e) {
console.log(e);
}
} else {
// 其他浏览器
let url = window.URL.createObjectURL(res.data)
let link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', fileName + suffix)
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
window.URL.revokeObjectURL(link.href);
}
}).catch((err) => {
console.log(err.message);
})
}`
使用方式
downloadFile('/api/download', {id}, '文件名')
2、网页空闲检测
- chrome浏览器其实提供了一个Idle DetectionAPI,来实现网页空闲状态的检测,但是这个API还是一个实验性特性,并且Firefox与Safari不支持。API参考
参数 | 类型 | 说明 | 默认值 |
---|---|---|---|
callback | () => void | 空闲时执行,即一定时长无操作时触发 | 必填 |
timeout | number | 时长s | 15s |
callback | boolean | 是否立即开始 | false |
- 开始 startDetection
- 结束 stopDetection
- 重置 restartDetection
js
function onIdleDetection(callback, timeout = 15, immediate = false) {
let pageTimer
let beginTime = 0
const onClearTimer = () => {
pageTimer && clearTimeout(pageTimer)
pageTimer = undefined
}
const onStartTimer = () => {
const currentTime = Date.now()
if (pageTimer && currentTime - beginTime < 100) {
return
}
onClearTimer()
beginTime = currentTime
pageTimer = setTimeout(() => {
callback()
}, timeout * 1000)
}
const onPageVisibility = () => {
// 页面显示状态改变时,移除延时器
onClearTimer()
if (document.visibilityState === 'visible') {
const currentTime = Date.now()
// 页面显示时,计算时间,如果超出限制时间则直接执行回调函数
if (currentTime - beginTime >= timeout * 1000) {
callback()
return
}
// 继续计时
pageTimer = setTimeout(
() => {
callback()
},
timeout * 1000 - (currentTime - beginTime)
)
}
}
const startDetection = () => {
onStartTimer()
document.addEventListener('keydown', onStartTimer)
document.addEventListener('mousemove', onStartTimer)
document.addEventListener('visibilitychange', onPageVisibility)
}
const stopDetection = () => {
onClearTimer()
document.removeEventListener('keydown', onStartTimer)
document.removeEventListener('mousemove', onStartTimer)
document.removeEventListener('visibilitychange', onPageVisibility)
}
const restartDetection = () => {
onClearTimer()
onStartTimer()
}
if (immediate) {
startDetection()
}
return {
startDetection,
stopDetection,
restartDetection
}
}
3、全屏
Document.documentElement**是一个会返回文档对象(document)的根元素的只读属性(如 HTML 文档的<html>元素)
js
/**
* 浏览器判断是否全屏
*/
export const fullscreenEnable = () => {
return document.isFullScreen || document.mozIsFullScreen || document.webkitIsFullScreen
}
/**
* 浏览器全屏
*/
export const reqFullScreen = () => {
if (document.documentElement.requestFullScreen) {
document.documentElement.requestFullScreen()
} else if (document.documentElement.webkitRequestFullScreen) {
document.documentElement.webkitRequestFullScreen()
} else if (document.documentElement.mozRequestFullScreen) {
document.documentElement.mozRequestFullScreen()
}
}
/**
* 浏览器退出全屏
*/
export const exitFullScreen = () => {
if (document.documentElement.requestFullScreen) {
document.exitFullScreen()
} else if (document.documentElement.webkitRequestFullScreen) {
document.webkitCancelFullScreen()
} else if (document.documentElement.mozRequestFullScreen) {
document.mozCancelFullScreen()
}
}
/**
* 浏览器全屏/恢复
*/
export const fullscreenToggel = () => {
if (fullscreenEnable()) {
exitFullScreen()
} else {
reqFullScreen()
}
}
4、与App交互
通用方法
js
/**
* 判断是安卓还是IOS环境
*/
function isAndroid() {
let u = navigator.userAgent
let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1 //android终端或者uc浏览器
// let isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) //ios终端
return isAndroid
}
/**
* 安卓 注册事件监听
*/
function connectWebViewJavascriptBridge(callback) {
if (window.WebViewJavascriptBridge) {
callback(WebViewJavascriptBridge)
} else {
document.addEventListener(
'WebViewJavascriptBridgeReady',
function () {
callback(WebViewJavascriptBridge)
},
false
)
}
}
/**
* ios 注册事件监听
*/
function setupWebViewJavascriptBridge(callback) {
var ua = navigator.userAgent.toLowerCase()
if (ua.match(/MicroMessenger/i) == 'micromessenger') {
//ios的ua中无miniProgram,但都有MicroMessenger(表示是微信浏览器)
} else {
if (!isAndroid()) {
if (window.WebViewJavascriptBridge) {
return callback(WebViewJavascriptBridge)
}
if (window.WVJBCallbacks) {
return window.WVJBCallbacks.push(callback)
}
window.WVJBCallbacks = [callback] // 创建一个 WVJBCallbacks 全局属性数组,并将 callback 插入到数组中
var WVJBIframe = document.createElement('iframe') // 创建一个 iframe 元素
WVJBIframe.style.display = 'none' // 不显示
WVJBIframe.src = 'https://__bridge_loaded__' // 设置 iframe 的 src 属性
document.documentElement.appendChild(WVJBIframe) // 把 iframe 添加到当前文导航上。
setTimeout(function () {
document.documentElement.removeChild(WVJBIframe)
}, 0)
}
}
}
// 安卓 ios公用执行方法
function onExecuteWebViewFn(funcName, cb, params = {}) {
if (isAndroid()) {
connectWebViewJavascriptBridge((bridge) => {
bridge.callHandler(funcName, params, cb)
})
} else {
setupWebViewJavascriptBridge(function (bridge) {
bridge.callHandler(funcName, params, cb)
})
}
}
demo 使用
vue 中使用需要在 mounted 注册
vue
<script>
export default {
// 第一种方法挂在全局 利用postMessage通讯
mounted() {
window.addEventListener('message', this.handleMessage)
},
beforeDestroy() {
window.removeEventListener('message', this.handleMessage)
},
methods: {
handleMessage(event) {
// 处理收到的消息
const message = event.data
// 执行逻辑
},
sendMessage() {
// 发送消息
const data = { foo: 'bar' }
window.parent.postMessage(data, '*')
}
},
// 第二种方法 WebViewJavascriptBridge
onLoad() {
if (!isAndroid()) {
try {
/**
* WKWebView有一个内容交互控制器,该对象提供了通过JS向WKWebView发送消息的途径。
* 需要设置MessageHandler,我把这个功能简称为MessageHandler
* */
window.webkit.messageHandlers.appFunc.postMessage('')
} catch (err) {
console.log('执行中错误')
}
}
// 监听回调方法
onExecuteWebViewFn('H5Func', (res) => {
console.log('H5Func')
})
}
}
</script>
5、打印机CLodop
JS
import { getLodop } from "@/src/utils/LodopFuncs.js" // web打印控件
Vue.prototype.CancelPrint = function(order) {
try {
let bookedItem = ""
if (order.booked == true) {
bookedItem = `
<p style='width:100%;text-align: center;font-size: 14.5pt;font-weight: bold;'>-- 标题 --</p>
`
}
const strHtml = `
<p style='width:100%;font-size: 18pt;font-weight: bold;text-align: center;'>#${order.orderNumber} 取消订单</p>
<p style='width:100%;text-align: center;font-size: 10.5pt;'>${order.businessName}</p>
${bookedItem}
<p style="width:100%;font-size: 8pt;font-weight: bold;">用户申请取消,请前往商家端处理</p>
<div style='width: 100%;overflow: hidden;zoom: 1;font-size: 0.7em;'>
<span style='float: left;'>订单编号:</span>
<span style='float: right;'>${order.orderCode}</span>
</div>
<div style='width: 100%;overflow: hidden;zoom: 1;font-size: 0.7em;'>
<span style='float: left;'>付款时间:</span>
<span style='float: right;'>${order.payTime}</span>
</div>
`
let LODOP = getLodop();
LODOP.PRINT_INITA(0, 0, 580, 60, "订单号");
LODOP.SET_PRINT_PAGESIZE("店铺名");
LODOP.ADD_PRINT_HTM(5, 0, "100%", "100%", strHtml);
LODOP.SET_PRINT_PAGESIZE(3, 580, 60, "");
// 设置打印份数
LODOP.SET_PRINT_COPIES(1)
let current_Print_Value = localStorage.getItem('currentPrintValue') || 0
LODOP.SET_PRINTER_INDEXA(current_Print_Value ? current_Print_Value : -1);
// LODOP.PREVIEW();
// 打印
LODOP.PRINT();
} catch (error) {
console.log('error----', error)
}
},