1

Page had the button which copies text to clipboard with code:

export class ClipboardService {
    static copyToClipboard(toCopy: string) : void {
        document.addEventListener('copy', (e : ClipboardEvent) => {
            e.clipboardData.setData('text/plain', toCopy);
            e.preventDefault();
        });
        document.execCommand('copy');
    }
} 

But after at use, this code Ctrl+C doesn't work. I need removeEventListener something like:

export class ClipboardService {
    static copyToClipboard(toCopy: string) : void {
        document.addEventListener('copy', (e : ClipboardEvent) => {
            e.clipboardData.setData('text/plain', toCopy);
            e.preventDefault();
        });
        document.execCommand('copy');

        document.removeEventListener('copy', (e : ClipboardEvent) => {
            e.clipboardData.??? // I stuck in this place.
        });
    }
}

How to go back to standard behavior for clipboard when text from a specific field copied?

Pavel
  • 2,005
  • 5
  • 36
  • 68
  • Possible duplicate of [event.clipboardData.setData in copy event](https://stackoverflow.com/questions/36270886/event-clipboarddata-setdata-in-copy-event) – Feras Al Sous Aug 14 '18 at 14:22
  • 3
    To remove the event listener, save the handler as a seperate function. You have to use the same function in both addEventListener and removeEventListener. `const doCopy = (e: .... ) => ...` and `.addEventListener( 'copy', doCopy );` and `.removeEventListener( 'copy', doCopy );` Two functions, even if they have exactly the same code inside, are considered different functions. – Shilly Aug 14 '18 at 14:27
  • @Shilly yes this work, thank You. Plese add your comment as an answer for the adoption. – Pavel Aug 14 '18 at 14:35

1 Answers1

12

The problem is that you're trying to remove the function by writing it again. In JS, two function, even with exactly the same code, are still different functions.

So you need to have a reference to the function to be able to use it in both calls:

export class ClipboardService {
static copyToClipboard(toCopy: string) : void {
    const create_copy = (e : ClipboardEvent) => {
        e.clipboardData.setData('text/plain', toCopy);
        e.preventDefault();
    };
    document.addEventListener('copy', create_copy );
    document.execCommand('copy');
    document.removeEventListener('copy', create_copy );
}

}

Shilly
  • 8,511
  • 1
  • 18
  • 24