最近的wap项目开发中有这样一个需求:
点击“分享”按钮会生成分享链接,然后自动将该链接复制到剪贴板
一开始以为很好做:
点击“分享”按钮时调用生成分享链接的接口,然后在回调中执行
document.execCommand('copy') 就好啦
简单示例:
<div class="share-box">
<input type="text" class="share-link" value="分享链接" />
<button class="share-btn">分享</button>
</div>
$('.share-btn').on('click', function() {
$.ajax({
url: '/echo/json/',
method: 'post'
}).then(rs => {
$('.share-link').val('https://xxx.xxx.com/share/xxx').select()
document.execCommand('copy')
})
})
然而,现实总会狠狠打脸
回调中的document.execCommand('copy')
并没有执行
效果查看:http://jsfiddle.net/hysunny/939upv6n/
查看规范后得知:
These are the steps to follow when triggering copy, cut or paste actions through a scripting API:
1. Execute the corresponding action synchronously.
2. Use the action’s return value as the return value for the API call.
Note: Copy and cut commands triggered through a scripting API will only affect the contents of the real clipboard if the event is dispatched from an event that is trusted and triggered by the user, or if the implementation is configured to allow this. Paste commands triggered through a scripting API will only fire paste events and give access to clipboard contents if the implementation is configured to allow this. How implementations can be configured to allow read or write access to the clipboard is outside the scope of this specification.
也就是说:document.execCommand('copy')
必须是由用户触发,并且这个操作是同步地。
所以,这个需求并不是我不想做,而是无能为力啊(´_ゝ`)
最后,改成了点击“分享”生成链接后再弹出个弹窗,然后再点击“复制链接”按钮后复制链接,简单示例:
<div class="share-box">
<input type="text" class="share-link" value="分享链接" />
<button class="share-btn">分享</button>
<button class="copy-link">复制链接</button>
</div>
$('.share-btn').on('click', function() {
$.ajax({
url: '/echo/json/',
method: 'post'
}).then(rs => {
$('.share-link').val('https://xxx.xxx.com/share/xxx')
})
})
$('.copy-link').on('click', function() {
$('.share-link').select()
document.execCommand('copy')
})
网友评论