Add Reference link when the text is copied from your Website – Javascript Hack

Updated on September 3, 2017

If you ever wished to add a reference or source url to the copied text from your website, then here’s a simple Javascript solution from C.Bavota. The idea of doing this is to provide credits to the source from where the text was copied. In fact, it politely tells the copier that you should respect someone’s work and at least provide a link back to the source. However, this method doesn’t intent to prevent plagiarism completely, but a step towards it.

The method involves in calling a Javascript function upon copy event and append a source URL to the copied text.

Note: The below code will not work on Internet Explorer.

Capture copied text javascript

Copy and paste the below script at the footer of your website.

function addLink() {
    
    var selection = window.getSelection();
    pagelink = ". Read more at: " + document.location.href;
    copytext = selection + pagelink;
    
    newdiv = document.createElement('div');

    newdiv.style.position = 'absolute';
    newdiv.style.left = '-99999px';

    document.body.appendChild(newdiv);
    newdiv.innerHTML = copytext;
    selection.selectAllChildren(newdiv);

    window.setTimeout(function () {
        document.body.removeChild(newdiv);
    }, 100);
}
document.addEventListener('copy', addLink);

That’s it. Now copy few texts from your website and try pasting it in your favorite editor. Love it? Say thanks to C. Bavota

Someone have a solution for IE browser? Let me know as comments.

Was this article helpful?

Related Articles

Leave a Comment