Skip to content

Instantly share code, notes, and snippets.

@av1m
Created August 12, 2021 18:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save av1m/9ff67eaee54cc22e202e932eba04c347 to your computer and use it in GitHub Desktop.
Save av1m/9ff67eaee54cc22e202e932eba04c347 to your computer and use it in GitHub Desktop.
Javascript that allow to add a text when a user copy
<html>
Hello World
<script>
function addLink() {
var body_element = document.getElementsByTagName('body')[0];
var selection;
selection = window.getSelection();
var pagelink = " (link= " + window.location.href +")";
var copytext = selection + pagelink;
var newdiv = document.createElement('div');
newdiv.style.position='absolute';
newdiv.style.left='-99999px';
body_element.appendChild(newdiv);
newdiv.innerHTML = copytext;
selection.selectAllChildren(newdiv);
window.setTimeout(function() {
body_element.removeChild(newdiv);
},0);
}
document.oncopy = addLink;
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment