0

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?

Eli Tref
  • 25
  • 4
  • 2
    No. As you said yourself "*all document.execCommand('copy') calls must take place as a direct result of a user action*" – derpirscher Dec 27 '22 at 16:14
  • It is ***impossible*** to do this without a user event. For safety reasons, the web browser will not run the command unless it was executed due to an event from the user, such as a button press. In conclusion, the answer is: No, you cannot do this without clicking. – Paxon Kymissis Dec 27 '22 at 16:43

1 Answers1

-1

using document.execCommand('copy') in input tow error: 1.input not have disabled class type 2.input not have hidden and display

so?fix just add a input it set class style for opacity:0; and then hide select this input copy text.

  • Still, the copy won't be executed unless is the direct result of some user interaction (eg a click ...) – derpirscher Dec 27 '22 at 17:32
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 28 '22 at 09:29