This is Founder's blog - Subscribe RSS - Founder's blog - About

JavaScript: injecting extra info to copy-pasted text

Dec 24 2013 :: by Alex

You've seen this many times - when you copy and paste text from a website - a reference link to the source appears at the bottom, sometimes along with a copyright notice. Something like "read more at". Some SEOs say this can be good source of backlinks so I tried to figure out how these sites do it... Turns out most of the sites use a service called "Tynt". But Tynt also traces visitor actions on a website (mouse moves, clicks etc), which I personally don't like.

Here's the JavaScript code that will inject extra info to copied web text. What is does is basically creating an invisible DOM-element and filling it with the html-code being copied (adding the extra info).

$("body").bind('copy', function (e) {
	if (typeof window.getSelection == "undefined") return; //IE8 or earlier...
	var body_element = document.getElementsByTagName('body')[0];
	var selection = window.getSelection();
	//if the selection is short let's not annoy our users
	if (("" + selection).length < 30) return;

	//create a div outside of the visible area
	//and fill it with the selected text
	var newdiv = document.createElement('div'); = 'absolute'; = '-99999px';
	//we need a <pre> tag workaround
	//otherwise the text inside "pre" loses all the line breaks!
	if (selection.getRangeAt(0).commonAncestorContainer.nodeName == "PRE") {
		newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
	newdiv.innerHTML += "<br /><br />Read more at: <a href='"
	+ document.location.href + "'>"
	+ document.location.href + "</a> &copy;";
	window.setTimeout(function () { body_element.removeChild(newdiv); }, 200);

Back to the blog or Subscribe RSS - Founder's blog if you liked the article