How to get selected text in JavaScript as a string while including alt text from images using document.getSelection()?

I’m trying to write a function that triggers when the user copies text, the function should add the selected text to the clipboard minus any blank lines. Consider the following HTML:

<html>
Blah blah
<br><br>
<img src="https://en.wikipedia.org/static/images/icons/wikipedia.png" alt="alt" />
<br><br>
blah blah
</html>

This gives the following result when copying the entire page:

Blah blah

alt

blah blah

Great, now I just need to intercept the copy event and remove the blank lines. Add the following script to the above example:

<script>
document.addEventListener('copy', (event) => {
    var selectedText = document.getSelection().toString();
    //Code to remove blank lines will go here
    event.clipboardData.setData('text/plain', selectedText);
    event.preventDefault();
});
</script>

But now when you copy the entire page you get the following result:

Blah blah



blah blah

It skips the alt text of the image for some reason, now it replaces it with another blank line. Why?

My first thought is that toString() is somehow removing it, which would be very problematic since I need that to manipulate the copied text, but if I don’t include toString() I get the same result.

Why is document.getSelection() giving me a different result than when I copy the page without it?