Javascript: Hijack Copy?

I just read The Times Online, and I wanted to copy some text from the article and send it to a friend, but I noticed that when I did this, he automatically added a link to the article in what I had copied.

This is not a feature of my IM client, so I assume this was due to some javascript on the Times website.

How would I do this if I wanted to implement it on my site? Basically, I would have to grab the copy operation and add the article URL to the end of the copied content, right? Thoughts?

Here's an article I read for reference: http://www.time.com/time/health/article/0,8599,1914857,00.html

+4
source share
5 answers

This is a breeze with jQuery (which is used on your site):

$("body").bind('copy', function(e) { // The user is copying something }); 

You can use the jQuery Search and Share plugin that does this exact thing when someone copies over 40 characters from your site: http://www.latentmotion.com/search-and-share/

The site you linked to seems to be using Tynt Insight to do this.

+5
source

They use the free Tynt service. If you want to do the same, just use the same service.

+1
source

Which browser are you using (and which version)?

In some new browsers, the user either asks if the website can access the buffer, or if it is simply not allowed. Other browsers (e.g. IE 6) allow this, and websites can easily read and write to the copy buffer.

Here is the code (IE only)

 clipboardData.setData("Text", "I just put this in the clipboard using JavaScript"); 
0
source

The "Copy and paste Hijacker" jQuery plugin does exactly what you want and seems more suitable for your purposes than Tynt or Search and Share: http://plugins.jquery.com/project/copypaste

You can easily format the copied content, specify the maximum or minimum characters and easily include the page title or URL in the copied content exactly where you want.

0
source

I recently noticed this on another website and wrote a blog post about how it works. The jQuery example does not seem to actually change what the user copies and pastes, it just adds a new context menu.

In short:

 var content = document.getElementById("content"); content.addEventListener("copy", oncopy); function oncopy() { var newEl = document.createElement("p"); document.body.appendChild(newEl); newEl.innerHTML = "In your copy, messing with your text!"; var selection = document.getSelection(); var range = selection.getRangeAt(0); selection.selectAllChildren(newEl); setTimeout(function() { newEl.parentNode.removeChild(newEl); selection.removeAllRanges(); selection.addRange(range); }, 0) } 

setTimeout at the end is important because it does not work if the last part is executed immediately.

This example replaces the selected text at the last minute with my selected line. You can also grab an existing selection and add whatever you want to the end.

0
source

All Articles