目录
一、针对h5和APP端(ios和android端,都由uniapp打包生成)的复制:
二、针对h5的iframe,ios和android端通过webview嵌套我们网页时(ios和android端采用原生开发)。
针对h5和APP端的复制,只需要区别APP端需要调用uni.setClipboardData方法,h5那边必须使用document.execCommand('Copy')执行复制就行了。
- function copy(res,isToast=true){
- // #ifdef H5
- let oInput = document.createElement('input')
- oInput.value = res
- document.body.appendChild(oInput)
- oInput.select() // 选择对象
- document.execCommand('Copy') // 执行浏览器复制命令
- if(isToast){
- uni.showToast({
- title: "复制成功!",
- duration: 2000,
- icon: "none",
- });
- }
- oInput.remove()
- // #endif
- // #ifndef H5
- uni.setClipboardData({
- data: res,
- success: function () {
- if(isToast){
- uni.showToast({
- title: "复制成功!",
- duration: 2000,
- icon: "none",
- });
- }
- },
- });
- // #endif
- }
当我们的网页需要在其他h5项目中用iframe嵌套,APP端那边使用webview嵌套时,h5和android那边的复制是可以的,但是ios的复制就不行了,网上找了很多方法都不行,最后只能让那边ios开发人员手动提供一个方法进行调用。
window.webkit.messageHandlers.ioscopy.postMessage(res)
这段代码是js调用ios方法,其中ioscopy是ios那边手动实现的一个复制方法,并不是本来就有的。
- function copy(res,isToast=true,title="复制成功。"){
- if(uni.getSystemInfoSync().platform=='ios'){ //ios兼容处理
- window.webkit.messageHandlers.ioscopy.postMessage(res);
- if(isToast){
- uni.showToast({
- title: title,
- duration: 2000,
- icon: "none",
- });
- }
- return;
- }
- // #ifdef H5
- let oInput = document.createElement('input')
- oInput.value = res
- document.body.appendChild(oInput)
- oInput.select() // 选择对象
- document.execCommand('Copy') // 执行浏览器复制命令
- if(isToast){
- uni.showToast({
- title: title,
- duration: 2000,
- icon: "none",
- });
- }
- oInput.remove()
- // #endif
- // #ifndef H5
- uni.setClipboardData({
- data: res,
- success: function () {
- if(isToast){
- uni.showToast({
- title: title,
- duration: 2000,
- icon: "none",
- });
- }
- },
- });
- // #endif
- }
有些浏览器的复制功能并不生效,比如红米官方自带的浏览器,其实并不是复制方法存在浏览器兼容问题,而是用户在第一次进入网页的时候将复制功能给禁用了,后面无论你换成什么复制方法,浏览器都无法复制。
可以在 浏览器->设置->隐私防护->隐私保护->读取或写入剪切板 进行查看。