0

This text is a link. How do I put this into the copy buffer (e.g. via navigator.clipboard.writeText()) so that when the user pastes it somewhere else it retains the link text as well as the link itself?

Thanks in advance!

Pichler
  • 59
  • 5
  • Welcome to StackOverflow @Pichler, Do you want it to be pasted as an html element like in gmail, doc etc or as a simple text in a text field, is there anything that you have tried and the result of same ? – Harsh Gundecha Aug 20 '21 at 08:19
  • I want the link to be pasted into other applications such as thunderbird or google docs. I tried to use `navigator.clipboard.writeText('Link')` which just puts the whole html element in plain text into the copy buffer – Pichler Aug 20 '21 at 08:26
  • Does this answer your question? [javascript copy rich text contents to clipboard](https://stackoverflow.com/questions/23934656/javascript-copy-rich-text-contents-to-clipboard) – Harsh Gundecha Aug 20 '21 at 12:15

2 Answers2

0

When u use addEventListener, you can extract all information from the event.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test page</title>
</head>
<body>
    <a class="link" href="https://stackoverflow.com/">Stackoverflow</a>

    <script>
        const linkComponent = document.querySelector('.link');

        linkComponent.addEventListener('click', (event) => {
            event.preventDefault(); // This will prevent the default action (going to link)
            navigator.clipboard.writeText(`${event.target.innerHTML} - ${event.path[0].href}`);
        });
    </script>
</body>
</html>
samsepi
  • 41
  • 4
0

I use ClipboardJs, it work for gmail or other email clients

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.8/clipboard.min.js"></script>
</head>
<body>
<div id="container">
    <a href="https://google.com">test link</a>
</div>
<button class="btn" data-clipboard-action="copy" data-clipboard-target="#container">Click me</button>
<script>
    let clipboard = new ClipboardJS(".btn", {})
        .on("success", function () {
            console.log('success')
        })
        .on("error", function () {
            console.log('error')
        });
</script>
</body>
</html>
mldev
  • 1