As we all know, copyright is important nowadays. Therefore, I put up a piece of JavaScript code to add a copyright notice to the content copied by user. In this article, I will share with you the approach and explain the details.
The JavaScript code:
document.addEventListener('copy', function (event) { var clipboardData = event.clipboardData || window.clipboardData; if (!clipboardData) { return; } var text = window.getSelection().toString(); if (text) { event.preventDefault(); clipboardData.setData('text/plain', text + '\r\nCopyright to SiteMaster'); } });
As we can see, we first listen to the copy event. Once the copy event is triggered and there is data in the clipboard. We prevent the browser default behavior with event.preventDefault(). Then we add the copyright notice to the end of the selected text and paste it to the clipboard.
In conclusion, we interrupt the default copy behavior and add in our notice to the content for pasting.