Event listener 'Copy' doesn't work with "Copy Link Address"

737 views Asked by At

I want to modify the clipboard so that it becomes the regex match. And that works - as long as I use Ctrl+C or just "Copy". If I click on "Copy link address" (or "Copy link location"), the event listener doesn't seem to see the copied thing at all. Here's the screen recording: https://i.stack.imgur.com/L4bQD.gif

What am I doing wrong?

<html>
<meta charset="ISO-8859-1">
<div class="source">
    <a href="https://www.example.com/example">https://www.example.com/example</a>
</div>
<div class="target" contenteditable="true">Copy the link above here</div>
</html>

<script>
    var regex = /\w{2,}.\w{2,}.\w{2,}/;

    document.body.addEventListener('copy', (event) => {
        const selection = document.getSelection();
        console.log(selection.toString());
        event.clipboardData.setData('text/plain', selection.toString().match(regex));
        event.preventDefault();
    });
</script>
1

There are 1 answers

0
retiredgoblin On BEST ANSWER

I have found the answer - this is intentional, as the documentation explains in the Security Considerations:

Enabling authors to change what is copied by a user, or to make an automated copy of something that was never selected and allowing unrestricted calls to paste information can raise various security concerns.

Some example scenarios include:

  • A user selects a link and copies it, but a different link is copied to the clipboard. The effect of this can range from an unexpected result on pasting to an attempted "phishing" attack.