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.
oh_cripes
source share