I have a site on http where after publishing a post, I need to copy the url of this post to the clipboard.
I made the observer
const observer = new MutationObserver(function (mutations, mutationInstance) {
const link = document.querySelector('#message > p > a')
if (link) {
unsecuredCopyToClipboard(link.href)
mutationInstance.disconnect()
}
})
observer.observe(document, {
childList: true,
subtree: true,
})
and that function
function unsecuredCopyToClipboard(text) {
const textArea = document.createElement('textarea')
textArea.value = text
document.body.appendChild(textArea)
textArea.focus()
textArea.select()
console.log(window.getSelection().toString())
try {
var successful = document.execCommand('copy')
var msg = successful ? 'successful' : 'unsuccessful'
console.log('Fallback: Copying text command was ' + msg)
} catch (err) {
console.error('Unable to copy to clipboard', err)
}
document.body.removeChild(textArea)
}
I see in the console correct selection (the link I need) and a message: Fallback: Copying text command was unsuccessful
I think it's because all document.execCommand('copy') calls must take place as a direct result of a user action, e.g. click event handler - How do I copy to the clipboard in JavaScript?
So, is there any way to get the link I need in the clipboard without clicking?