ios下js复制到粘贴板_在iOS中使用Javascript复制到剪贴板

I'm using this function to copy a URL to the clipboard:

function CopyUrl($this){

var querySelector = $this.next().attr("id");

var emailLink = document.querySelector("#"+querySelector);

var range = document.createRange();

range.selectNode(emailLink);

window.getSelection().addRange(range);

try {

// Now that we've selected the anchor text, execute the copy command

var successful = document.execCommand('copy', false, null);

var msg = successful ? 'successful' : 'unsuccessful';

if(true){

$this.addClass("copied").html("Copied");

}

} catch(err) {

console.log('Oops, unable to copy');

}

// Remove the selections - NOTE: Should use

// removeRange(range) when it is supported

window.getSelection().removeAllRanges();

}

Everything works fine on desktop browsers, but not on iOS devices, where my function returns successfully, but the data isn't copied to the clipboard at all. What's causing this and how could I solve this problem?

解决方案

There's no problem with your code. However on iOS Safari there are some restrictions (which actually are security measures) to the Clipboard API:

It fires copy events only on a valid selection and cut and paste only in focused editable fields.

It only supports OS clipboard reading/writing via shortcut keys, not through document.execCommand(). Note that "shorcut key" means some clickable (e.g. copy/paste action menu or custom iOS keyboard shortcut) or physical key (e.g. connected bluetooth keyboard).

It doesn't support the ClipboardEvent constructor.

So (at least as of now) it's not possible to programmatically copy some text/value in the clipboard on an iOS device using Javascript. Only the user can decide whether to copy something.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值