xc-app/utils/uniCopyUtils.js

78 lines
2.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
uni-app复制文本插件支持三端 小程序 App H5
*/
import { currentLang } from '@/config/baseConfig.js'
const i18nEnums = {
'zh-CN': {
msgSuccess: '复制成功~',
msgFail: '复制失败~',
msgBrowserErr: '浏览器不支持!',
msgFailErr: '复制失败请检查h5中调用该方法的方式是不是用户点击的方式调用的如果不是请改为用户点击的方式触发该方法因为h5中安全性不能js直接调用',
},
'zh-TW': {
msgSuccess: '複製成功~',
msgFail: '複製失敗~',
msgBrowserErr: '瀏覽器不支持!',
msgFailErr: '複製失敗請檢查h5中調用該方法的管道是不是用戶點擊的管道調用的如果不是請改為用戶點擊的管道觸發該方法因為h5中安全性不能js直接調用',
},
'en-US': {
msgSuccess: 'Copy succeeded~',
msgFail: 'Copy failed~',
msgBrowserErr: 'Browser does not support',
msgFailErr: 'Copy failure. Please check the way in which H5 invokes this method, whether it is called by user clicking. If not, please trigger the method instead of user clicking, because H5 security can not be called directly by JS.',
}
}
export default function uniCopy({content, success, error}) {
let _currentLang = currentLang
try {
const _lang = uni.getStorageSync('lang')
// 判断当前设备语言是否为我们所支持的
if (Object.keys(i18nEnums).includes(_lang)) {
_currentLang = _lang
}
} catch (e) {}
content = typeof content === 'string' ? content : content.toString() // 复制内容,必须字符串,数字需要转换为字符串
/**
* 小程序端 和 app端的复制逻辑
*/
//#ifndef H5
uni.setClipboardData({
data: content,
success: function() {
success(i18nEnums[_currentLang].msgSuccess)
},
fail:function(){
error(i18nEnums[_currentLang].msgFail)
}
});
//#endif
/**
* H5端的复制逻辑
*/
// #ifdef H5
if (!document.queryCommandSupported('copy')) { //为了兼容有些浏览器 queryCommandSupported 的判断
// 不支持
error(i18nEnums[_currentLang].msgBrowserErr)
}
let textarea = document.createElement("textarea")
textarea.value = content
textarea.readOnly = "readOnly"
document.body.appendChild(textarea)
textarea.select() // 选择对象
textarea.setSelectionRange(0, content.length) //核心
let result = document.execCommand("copy") // 执行浏览器复制命令
if(result){
success(i18nEnums[_currentLang].msgSuccess)
}else{
error(i18nEnums[_currentLang].msgFailErr)
}
textarea.remove()
// #endif
}