Skip to content

Instantly share code, notes, and snippets.

@sandcastle
Created July 17, 2017 06:38
Show Gist options
  • Save sandcastle/00aaa8a820061c899edf76c3ed3c8bac to your computer and use it in GitHub Desktop.
Save sandcastle/00aaa8a820061c899edf76c3ed3c8bac to your computer and use it in GitHub Desktop.
A copy to clipboard function (in typescript)
export const copyToClipboard = (url: string) => {
document.addEventListener('copy', (e: ClipboardEvent) => {
e.clipboardData.setData('text/plain', url);
e.preventDefault();
document.removeEventListener('copy');
});
document.execCommand('copy');
};
@curtisault
Copy link

curtisault commented Mar 27, 2018

The function removeEventListener will pass TSLint if you pass it the correct amount of parameters:

document.removeEventListener('copy', this.ClipboardEvent);

@quasarea
Copy link

Should be:
document.removeEventListener('copy', this.e);

@yatsukvn
Copy link

changed a little:

public copyToClipboard(data: string): void {
const listener = (e: ClipboardEvent) => {
e.clipboardData.setData('text/plain', data);
e.preventDefault();
document.removeEventListener('copy', listener);
};
document.addEventListener('copy', listener);
document.execCommand('copy');
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment