uniapp文本复制到剪切版的坑

事情发生的很奇怪,复制功能用的vue-clipboard2依赖库,部分 ios 手机用户,商城购物时,复制订单号有效,但没法粘贴。排查下来,问题锁定在 ios 手机升级的新系统版本,无法复制有效,粘贴无效。

复制粘贴功能的实现

execCommand 方法

用法,详见

该方法已被弃用,但不影响正常使用。它允许运行命令来操纵可编辑内容区域的元素。使用方式如下:

1
2
3
4
5
6
7
8
const copyText = (val) => {
const textArea = document.createElement('textArea');
textArea.value = val;
document.body.appendChild(textArea);
textArea.select();
document.execCommand('copy');
document.body.removeChild(textArea);
};

复测了下,发现 ios 手机在浏览器下,点击复制按钮,整个页面会跳动一下。查起原因,创建的textArea不在页面可视区域之内,然后执行textArea.select(),就会触发浏览器的控件跳转行为,页面会滚动到 textArea 所在位置。然后执行完又快速移除了,就会形成闪动的这么一个现状。

那就给元素加固定定位。修改后的代码如下:

1
2
3
4
5
6
7
8
9
const textArea = document.createElement('textArea');
textArea.value = val || '';
textArea.style.cssText = 'position: fixed; top: -999px; left: -999px; opacity: 0;';
textArea.setAttribute('readonly', 'readonly');
document.body.appendChild(textArea);

textArea.select();
document.execCommand('copy');
document.body.removeChild(textArea);

复测下,体验正常了。

用法,详见

这是个异步的方法,兼容性不太好,Safari 支持 13.1 及以上的。结合 execCommand 代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const copyText = async (val) => {
if (navigator.clipboard && navigator.permissions) {
await navigator.clipboard.writeText(val);
} else {
const textArea = document.createElement('textArea');
textArea.value = val || '';
textArea.style.cssText = 'position: fixed; top: -999px; left: -999px; opacity: 0;';
textArea.setAttribute('readonly', 'readonly');
document.body.appendChild(textArea);

textArea.select();
document.execCommand('copy');
document.body.removeChild(textArea);
}
};

调用 APP 交互 SDK 方法

也只能局限于 APP 端内 H5 使用,端外 H5 已然得用上面的方法。

uni.setClipboardData

用法,详见

相关链接

[1] JS 复制文字到剪贴板的坑及完整方案