javascript - How to add extra info to copied web text -


some websites use javascript service tynt appends text copied content.

if copy text site using , paste link original content @ bottom of text.

tynt tracks happens. it's neat trick done.

their script doing impressive - rather try manipulate clipboard (which older versions of ie lets them default , should turned off) manipulate actual selection.

so when select block of text content added hidden <div> included in selection. when paste style ignored , link appears.

this easy simple blocks of text, nightmare when consider selections possible across complex html in different browsers.

i'm developing web application - don't want able track content copied , info contain contextual, rather link. tynt's service isn't appropriate in case.

does know of open source javascript library (maybe jquery plug in or similar) provides similar functionality doesn't expose internal application data?

there 2 main ways add info copied web text.

1. manipulating selection

the idea watch copy event, append hidden container our info dom, , extend selection it.
method adapted this article c.bavota. check jitbit's version more complex case.

  • browser compatibility: major browsers, ie > 8.
  • demo: jsfiddle demo.
  • javascript code:
     function addlink() {         //get selected text , append info         var selection = window.getselection(),             pagelink = '<br /><br /> read more at: ' + document.location.href,             copytext = selection + pagelink,             newdiv = document.createelement('div');          //hide newly created container         newdiv.style.position = 'absolute';         newdiv.style.left = '-99999px';          //insert container, fill extended text, , define new selection         document.body.appendchild(newdiv);         newdiv.innerhtml = copytext;         selection.selectallchildren(newdiv);          window.settimeout(function () {             document.body.removechild(newdiv);         }, 100);     }      document.addeventlistener('copy', addlink); 

2. manipulating clipboard

the idea watch copy event , directly modify clipboard data. possible using clipboarddata property. note property available in major browsers in read-only; setdata method available on ie.

  • browser compatibility: ie > 4.
  • demo: jsfiddle demo.
  • javascript code:
     function addlink(event) {         event.preventdefault();          var pagelink = '\n\n read more at: ' + document.location.href,             copytext =  window.getselection() + pagelink;          if (window.clipboarddata) {             window.clipboarddata.setdata('text', copytext);         }     }      document.addeventlistener('copy', addlink); 

Comments

Popular posts from this blog

c++ - Delete matches in OpenCV (Keypoints and descriptors) -

java - Could not locate OpenAL library -

sorting - opencl Bitonic sort with 64 bits keys -