Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
Uni – app clipboard
Company has a team that rent a house rental project function, and the remaining in the H5 function at the beginning, mainly in the WeChat development by the public, and recently began after online APP, part of the function changes, including function to add a new member of the team to do the new operation process, which based on WeChat public, WeChat browser share the qr code, Now similar to a treasure share invitation code to complete the operation.
So that’s where the user’s clipboard operation comes in.
Then, to my surprise, uni-App’s clipboard operation does not support H5.
Other apps, small program support, do not support H5, you are not angry?
No, I’ll do whatever you don’t support. Whisper.
Familiarize yourself with the built-in clipboard operation API
uni.setClipboardData({ data: 'Text to copy' })
Copy the code
In H5, the element’s JavaScript is used.
const textarea = document.createElement('textarea')
textarea.value = data
textarea.readOnly = true
document.body.appendChild(textarea)
textarea.select()
textarea.setSelectionRange(0, data.length)
document.execCommand('copy')
textarea.remove()
Copy the code
Replication is implemented by adding a Textarea text field, the operation related API.
Finally, combine them and encapsulate them into one method.
setClipboardData(data) {
return new Promise((success, fail) = > {
// #ifndef H5
uni.setClipboardData({ data, success, fail })
// #endif
// #ifdef H5
const textarea = document.createElement('textarea')
textarea.value = data
textarea.readOnly = true
document.body.appendChild(textarea)
textarea.select()
textarea.setSelectionRange(0, data.length)
document.execCommand('copy')
textarea.remove()
success(data)
// #endif})}Copy the code
Call the following
setClipboard(data){
this.setClipboardData(data)
.then(res= > {}) // Successful callback
.catch(err= > {}) // Failed callback
}
Copy the code