最近的wap項(xiàng)目開發(fā)中有這樣一個(gè)需求:
點(diǎn)擊“分享”按鈕會(huì)生成分享鏈接,然后自動(dòng)將該鏈接復(fù)制到剪貼板
一開始以為很好做:
點(diǎn)擊“分享”按鈕時(shí)調(diào)用生成分享鏈接的接口,然后在回調(diào)中執(zhí)行
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')
})
})
然而,現(xiàn)實(shí)總會(huì)狠狠打臉
回調(diào)中的document.execCommand('copy')
并沒有執(zhí)行
效果查看:http://jsfiddle.net/hysunny/939upv6n/
查看規(guī)范后得知:
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')
必須是由用戶觸發(fā),并且這個(gè)操作是同步地。
所以,這個(gè)需求并不是我不想做,而是無能為力啊(′_ゝ`)
最后,改成了點(diǎn)擊“分享”生成鏈接后再彈出個(gè)彈窗,然后再點(diǎn)擊“復(fù)制鏈接”按鈕后復(fù)制鏈接,簡單示例:
<div class="share-box">
<input type="text" class="share-link" value="分享鏈接" />
<button class="share-btn">分享</button>
<button class="copy-link">復(fù)制鏈接</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')
})