getSelection removes links from selection? - javascript

I'm using following code to add my copyright when a text get selected in my website. Everything works well, except that if user selects an area which has link, getSelection() method does not return the link. It just returns the plain text.
I want to allow user to copy my website content as usual, without disturbing the style and content. I'm just looking for a way to add a copyright to the end of selection.
Any way?
Regards
<script type="text/javascript">
function addLink() {
var body_element = document.getElementsByTagName('body')[0];
var selection;
selection = window.getSelection();
var pagelink = "<br /><br /> Read more at: <a href='"+document.location.href+"'>"+document.location.href+"</a><br />Copyright © c.bavota"; // change this if you want
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>

You need to get the HTML of the selection, instead of the text, then you can append your link.
Have a look at this question.

Related

How to add extra info to copied web text [Beginning and End]

Following javascript is used to append a link at the end of the copied text. I want to add the link in the beginning of the text, not at the bottom. How can I do it?
EDIT: Got the answer for the above question, now i would like to know how to add it in the beginning and end at the same time. Also would like to know how to add it in the middle of the copied text.
function addLink() {
//Get the selected text and append the extra info
var selection = window.getSelection(),
pagelink = '<br /><br /> Read more at: ' + document.location.href,
copytext = selection + pagelink,
newdiv = document.createElement('div');
//hide the newly created container
newdiv.style.position = 'absolute';
newdiv.style.left = '-99999px';
//insert the container, fill it with the extended text, and define the new selection
document.body.appendChild(newdiv);
newdiv.innerHTML = copytext;
selection.selectAllChildren(newdiv);
window.setTimeout(function () {
document.body.removeChild(newdiv);
}, 100);
}
document.addEventListener('copy', addLink);

When copying selected text extra text is copied, How does it work? [duplicate]

Some websites now use a JavaScript service from Tynt that appends text to copied content.
If you copy text from a site using this and then paste you get a link to the original content at the bottom of the text.
Tynt also tracks this as it happens. It's a neat trick well done.
Their script for doing this is impressive - rather than try to manipulate the clipboard (which only older versions of IE lets them do by default and which should always be turned off) they manipulate the actual selection.
So when you select a block of text the extra content is added as a hidden <div> included in your selection. When you paste the extra style is ignored and the extra link appears.
This is actually fairly easy to do with simple blocks of text, but a nightmare when you consider all the selections possible across complex HTML in different browsers.
I'm developing a web application - I don't want anyone to be able to track the content copied and I would like the extra info to contain something contextual, rather than just a link. Tynt's service isn't really appropriate in this case.
Does anyone know of an open source JavaScript library (maybe a jQuery plug in or similar) that provides similar functionality but that doesn't expose internal application data?
2022 Update
More complex solution that handles rich text formatting. The 2020 solution is still relevant if you only deal with plain text.
const copyListener = (event) => {
const range = window.getSelection().getRangeAt(0),
rangeContents = range.cloneContents(),
pageLink = `Read more at: ${document.location.href}`,
helper = document.createElement("div");
helper.appendChild(rangeContents);
event.clipboardData.setData("text/plain", `${helper.innerText}\n${pageLink}`);
event.clipboardData.setData("text/html", `${helper.innerHTML}<br>${pageLink}`);
event.preventDefault();
};
document.addEventListener("copy", copyListener);
#richText {
width: 415px;
height: 70px;
border: 1px solid #777;
overflow: scroll;
}
#richText:empty:before {
content: "Paste your copied text here";
color: #888;
}
<h4>Rich text:</h4>
<p>Lorem <u>ipsum</u> dolor sit <b>amet</b>, consectetur <i>adipiscing</i> elit.</p>
<h4>Plain text editor:</h4>
<textarea name="textarea" rows="5" cols="50" placeholder="Paste your copied text here"></textarea>
<h4>Rich text editor:</h4>
<div id="richText" contenteditable="true"></div>
2020 Update
Solution that works on all recent browsers.
Note that this solution will strip rich text formatting (such as bold and italic), even when pasting into a rich text editor.
document.addEventListener('copy', (event) => {
const pagelink = `\n\nRead more at: ${document.location.href}`;
event.clipboardData.setData('text/plain', document.getSelection() + pagelink);
event.preventDefault();
});
Lorem ipsum dolor sit <b>amet</b>, consectetur <i>adipiscing</i> elit.<br/>
<textarea name="textarea" rows="7" cols="50" placeholder="paste your copied text here"></textarea>
[Older post - before the 2020 update]
There are two main ways to add extra info to copied web text.
Manipulating the selection
The idea is to watch for the copy event, then append a hidden container with our extra info to the dom, and extend the selection to it.
This method is adapted from this article by c.bavota. Check also jitbit's version for more complex case.
Browser compatibility: All major browsers, IE > 8.
Demo: jsFiddle demo.
Javascript code:
function addLink() {
//Get the selected text and append the extra info
var selection = window.getSelection(),
pagelink = '<br /><br /> Read more at: ' + document.location.href,
copytext = selection + pagelink,
newdiv = document.createElement('div');
//hide the newly created container
newdiv.style.position = 'absolute';
newdiv.style.left = '-99999px';
//insert the container, fill it with the extended text, and define the new selection
document.body.appendChild(newdiv);
newdiv.innerHTML = copytext;
selection.selectAllChildren(newdiv);
window.setTimeout(function () {
document.body.removeChild(newdiv);
}, 100);
}
document.addEventListener('copy', addLink);
Manipulating the clipboard
The idea is to watch the copy event and directly modify the clipboard data. This is possible using the clipboardData property. Note that this property is available in all major browsers in read-only; the setData method is only 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);
This is a vanilla javascript solution from a modified solution above but supports more browsers (cross browser method)
function addLink(e) {
e.preventDefault();
var pagelink = '\nRead more: ' + document.location.href,
copytext = window.getSelection() + pagelink;
clipdata = e.clipboardData || window.clipboardData;
if (clipdata) {
clipdata.setData('Text', copytext);
}
}
document.addEventListener('copy', addLink);
The shortest version for jQuery that I tested and is working is:
jQuery(document).on('copy', function(e)
{
var sel = window.getSelection();
var copyFooter =
"<br /><br /> Source: <a href='" + document.location.href + "'>" + document.location.href + "</a><br />© YourSite";
var copyHolder = $('<div>', {html: sel+copyFooter, style: {position: 'absolute', left: '-99999px'}});
$('body').append(copyHolder);
sel.selectAllChildren( copyHolder[0] );
window.setTimeout(function() {
copyHolder.remove();
},0);
});
Here is a plugin in jquery to do that
https://github.com/niklasvh/jquery.plugin.clipboard
From the project readme
"This script modifies the contents of a selection prior to a copy event being called, resulting in the copied selection being different from what the user selected.
This allows you to append/prepend content to the selection, such as copyright information or other content.
Released under MIT License"
Improving on the answer, restore selection after the alterations to prevent random selections after copy.
function addLink() {
//Get the selected text and append the extra info
var selection = window.getSelection(),
pagelink = '<br /><br /> Read more at: ' + document.location.href,
copytext = selection + pagelink,
newdiv = document.createElement('div');
var range = selection.getRangeAt(0); // edited according to #Vokiel's comment
//hide the newly created container
newdiv.style.position = 'absolute';
newdiv.style.left = '-99999px';
//insert the container, fill it with the extended text, and define the new selection
document.body.appendChild(newdiv);
newdiv.innerHTML = copytext;
selection.selectAllChildren(newdiv);
window.setTimeout(function () {
document.body.removeChild(newdiv);
selection.removeAllRanges();
selection.addRange(range);
}, 100);
}
document.addEventListener('copy', addLink);
Improvement for 2018
document.addEventListener('copy', function (e) {
var selection = window.getSelection();
e.clipboardData.setData('text/plain', $('<div/>').html(selection + "").text() + "\n\n" + 'Source: ' + document.location.href);
e.clipboardData.setData('text/html', selection + '<br /><br />Source');
e.preventDefault();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Example text with <b>bold</b> and <i>italic</i>. Try copying and pasting me into a rich text editor.</p>
Also a little shorter solution:
jQuery( document ).ready( function( $ )
{
function addLink()
{
var sel = window.getSelection();
var pagelink = "<br /><br /> Source: <a href='" + document.location.href + "'>" + document.location.href + "</a><br />© text is here";
var div = $( '<div>', {style: {position: 'absolute', left: '-99999px'}, html: sel + pagelink} );
$( 'body' ).append( div );
sel.selectAllChildren( div[0] );
div.remove();
}
document.oncopy = addLink;
} );
It's a compilation of 2 answers above + compatibility with Microsoft Edge.
I've also added a restore of the original selection at the end, as it is expected by default in any browser.
function addCopyrightInfo() {
//Get the selected text and append the extra info
var selection, selectedNode, html;
if (window.getSelection) {
var selection = window.getSelection();
if (selection.rangeCount) {
selectedNode = selection.getRangeAt(0).startContainer.parentNode;
var container = document.createElement("div");
container.appendChild(selection.getRangeAt(0).cloneContents());
html = container.innerHTML;
}
}
else {
console.debug("The text [selection] not found.")
return;
}
// Save current selection to resore it back later.
var range = selection.getRangeAt(0);
if (!html)
html = '' + selection;
html += "<br/><br/><small><span>Source: </span><a target='_blank' title='" + document.title + "' href='" + document.location.href + "'>" + document.title + "</a></small><br/>";
var newdiv = document.createElement('div');
//hide the newly created container
newdiv.style.position = 'absolute';
newdiv.style.left = '-99999px';
// Insert the container, fill it with the extended text, and define the new selection.
selectedNode.appendChild(newdiv); // *For the Microsoft Edge browser so that the page wouldn't scroll to the bottom.
newdiv.innerHTML = html;
selection.selectAllChildren(newdiv);
window.setTimeout(function () {
selectedNode.removeChild(newdiv);
selection.removeAllRanges();
selection.addRange(range); // Restore original selection.
}, 5); // Timeout is reduced to 10 msc for Microsoft Edge's sake so that it does not blink very noticeably.
}
document.addEventListener('copy', addCopyrightInfo);

Add tags around selected text in an element

How can I add <span> tags around selected text within an element?
For example, if somebody highlights "John", I would like to add span tags around it.
HTML
<p>My name is Jimmy John, and I hate sandwiches. My name is still Jimmy John.</p>
JS
function getSelectedText() {
t = (document.all) ? document.selection.createRange().text : document.getSelection();
return t;
}
$('p').mouseup(function(){
var selection = getSelectedText();
var selection_text = selection.toString();
console.log(selection);
console.log(selection_text);
// How do I add a span around the selected text?
});
http://jsfiddle.net/2w35p/
There is a identical question here: jQuery select text and add span to it in an paragraph, but it uses outdated jquery methods (e.g. live), and the accepted answer has a bug.
I have a solution. Get the Range of the selecion and deleteContent of it, then insert a new span in it .
$('body').mouseup(function(){
var selection = getSelectedText();
var selection_text = selection.toString();
// How do I add a span around the selected text?
var span = document.createElement('SPAN');
span.textContent = selection_text;
var range = selection.getRangeAt(0);
range.deleteContents();
range.insertNode(span);
});
You can see the DEMO here
UPDATE
Absolutly, the selection will be delete at the same time. So you can add the selection range with js code if you want.
You can simply do like this.
$('body').mouseup(function(){
var span = document.createElement("span");
if (window.getSelection) {
var sel = window.getSelection();
if (sel.rangeCount) {
var range = sel.getRangeAt(0).cloneRange();
range.surroundContents(span);
sel.removeAllRanges();
sel.addRange(range);
}
}
});
Fiddle
Reference Wrapping a selected text node with span
You can try this:
$('body').mouseup(function(){
var selection = getSelectedText();
var innerHTML = $('p').html();
var selectionWithSpan = '<span>'+selection+'</span>';
innerHTML = innerHTML.replace(selection,selectionWithSpan);
$('p').html(innerHTML);
});
and In your fiddle you are again opening a new <p> instead of a closing </p>. Update that please.
THIS WORKS (mostly*)!! (technically, it does what you want, but it needs HALP!)
JSFiddle
This adds <span ...> and </span> correctly, even if there are multiple instances of the selection in your element and you only care about the instance that's selected!
It works perfectly the first time if you include my commented line. It's after that when things get funky.
I can add the span tags, but I'm having a hard time replacing the plaintext with html. Maybe you can figure it out? We're almost there!! This uses nodes from getSelection. Nodes can be hard to work with though.
document.getElementById('d').addEventListener('mouseup',function(e){
var s = window.getSelection();
var n = s.anchorNode; //DOM node
var o = s.anchorOffset; //index of start selection in the node
var f = s.focusOffset; //index of end selection in the node
n.textContent = n.textContent.substring(0,o)+'<span style="color:red;">'
+n.textContent.substring(o,f)+'</span>'
+n.textContent.substring(f,n.textContent.length);
//adds the span tag
// document.getElementById('d').innerHTML = n.textContent;
// this line messes stuff up because of the difference
// between a node's textContent and it's innerHTML.
});

Javascript "getSelection" only if it's in a certain div

So I'm trying to collect what people are selecting on our site. Currently, it works EVERYWHERE, and I don't want that. I only want it if they are selecting in a certain DIV.
it's basically a simple modification to a script I found.
<script type="text/javascript">
function appendCopyright() {
var theBody = document.getElementsByClassName("sbReview")[0];
var selection;
selection = window.getSelection();
var copyrightLink = '<br /><br /> - Read more at: '+document.location.href+'<br />©2012 <? printf($product. ' & ' .$spOrganization); ?>';
var copytext = selection + copyrightLink;
var extra = document.createElement("div");
extra.style.position="absolute";
extra.style.left="-99999px";
theBody.appendChild(extra);
extra.innerHTML = copytext;
selection.selectAllChildren(extra);
window.setTimeout(function() {
theBody.removeChild(extra);
},0);
}
document.oncopy = appendCopyright;
I tried modifying selection = window.getSelection(); but it just broke it :(
Basically, I want the above code, ONLY to work in a certain div, not the whole body
Probably you shouldn't use document.oncopy, instead try using div.oncopy where div is the div element you are interested in.
var selection = getSelection().toString(); is your solution - getSelection() returns a Selection object and you can get the string just by using .toString() method. More properties and methods of Selection object could be found here: https://developer.mozilla.org/en-US/docs/DOM/Selection
According to the Mozilla JS docs the selection class has a method containsNode. The following should work.
function appendCopyright() {
var theBody = document.getElementsByClassName("sbReview")[0];
var selection;
selection = window.getSelection();
// HERE's THE GOODS
// set aPartlyContained to true if you want to display this
// if any of your node is selected
if(selection.containsNode(aNode, aPartlyContained)){
var copyrightLink = '<br /><br /> - Read more at: '+document.location.href+'<br />©2012 <? printf($product. ' & ' .$spOrganization); ?>';
var copytext = selection + copyrightLink;
var extra = document.createElement("div");
extra.style.position="absolute";
extra.style.left="-99999px";
theBody.appendChild(extra);
extra.innerHTML = copytext;
selection.selectAllChildren(extra);
window.setTimeout(function() {
theBody.removeChild(extra);
},0);
}
}
document.oncopy = appendCopyright;

How to add extra info to copied web text

Some websites now use a JavaScript service from Tynt that appends text to copied content.
If you copy text from a site using this and then paste you get a link to the original content at the bottom of the text.
Tynt also tracks this as it happens. It's a neat trick well done.
Their script for doing this is impressive - rather than try to manipulate the clipboard (which only older versions of IE lets them do by default and which should always be turned off) they manipulate the actual selection.
So when you select a block of text the extra content is added as a hidden <div> included in your selection. When you paste the extra style is ignored and the extra link appears.
This is actually fairly easy to do with simple blocks of text, but a nightmare when you consider all the selections possible across complex HTML in different browsers.
I'm developing a web application - I don't want anyone to be able to track the content copied and I would like the extra info to contain something contextual, rather than just a link. Tynt's service isn't really appropriate in this case.
Does anyone know of an open source JavaScript library (maybe a jQuery plug in or similar) that provides similar functionality but that doesn't expose internal application data?
2022 Update
More complex solution that handles rich text formatting. The 2020 solution is still relevant if you only deal with plain text.
const copyListener = (event) => {
const range = window.getSelection().getRangeAt(0),
rangeContents = range.cloneContents(),
pageLink = `Read more at: ${document.location.href}`,
helper = document.createElement("div");
helper.appendChild(rangeContents);
event.clipboardData.setData("text/plain", `${helper.innerText}\n${pageLink}`);
event.clipboardData.setData("text/html", `${helper.innerHTML}<br>${pageLink}`);
event.preventDefault();
};
document.addEventListener("copy", copyListener);
#richText {
width: 415px;
height: 70px;
border: 1px solid #777;
overflow: scroll;
}
#richText:empty:before {
content: "Paste your copied text here";
color: #888;
}
<h4>Rich text:</h4>
<p>Lorem <u>ipsum</u> dolor sit <b>amet</b>, consectetur <i>adipiscing</i> elit.</p>
<h4>Plain text editor:</h4>
<textarea name="textarea" rows="5" cols="50" placeholder="Paste your copied text here"></textarea>
<h4>Rich text editor:</h4>
<div id="richText" contenteditable="true"></div>
2020 Update
Solution that works on all recent browsers.
Note that this solution will strip rich text formatting (such as bold and italic), even when pasting into a rich text editor.
document.addEventListener('copy', (event) => {
const pagelink = `\n\nRead more at: ${document.location.href}`;
event.clipboardData.setData('text/plain', document.getSelection() + pagelink);
event.preventDefault();
});
Lorem ipsum dolor sit <b>amet</b>, consectetur <i>adipiscing</i> elit.<br/>
<textarea name="textarea" rows="7" cols="50" placeholder="paste your copied text here"></textarea>
[Older post - before the 2020 update]
There are two main ways to add extra info to copied web text.
Manipulating the selection
The idea is to watch for the copy event, then append a hidden container with our extra info to the dom, and extend the selection to it.
This method is adapted from this article by c.bavota. Check also jitbit's version for more complex case.
Browser compatibility: All major browsers, IE > 8.
Demo: jsFiddle demo.
Javascript code:
function addLink() {
//Get the selected text and append the extra info
var selection = window.getSelection(),
pagelink = '<br /><br /> Read more at: ' + document.location.href,
copytext = selection + pagelink,
newdiv = document.createElement('div');
//hide the newly created container
newdiv.style.position = 'absolute';
newdiv.style.left = '-99999px';
//insert the container, fill it with the extended text, and define the new selection
document.body.appendChild(newdiv);
newdiv.innerHTML = copytext;
selection.selectAllChildren(newdiv);
window.setTimeout(function () {
document.body.removeChild(newdiv);
}, 100);
}
document.addEventListener('copy', addLink);
Manipulating the clipboard
The idea is to watch the copy event and directly modify the clipboard data. This is possible using the clipboardData property. Note that this property is available in all major browsers in read-only; the setData method is only 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);
This is a vanilla javascript solution from a modified solution above but supports more browsers (cross browser method)
function addLink(e) {
e.preventDefault();
var pagelink = '\nRead more: ' + document.location.href,
copytext = window.getSelection() + pagelink;
clipdata = e.clipboardData || window.clipboardData;
if (clipdata) {
clipdata.setData('Text', copytext);
}
}
document.addEventListener('copy', addLink);
The shortest version for jQuery that I tested and is working is:
jQuery(document).on('copy', function(e)
{
var sel = window.getSelection();
var copyFooter =
"<br /><br /> Source: <a href='" + document.location.href + "'>" + document.location.href + "</a><br />© YourSite";
var copyHolder = $('<div>', {html: sel+copyFooter, style: {position: 'absolute', left: '-99999px'}});
$('body').append(copyHolder);
sel.selectAllChildren( copyHolder[0] );
window.setTimeout(function() {
copyHolder.remove();
},0);
});
Here is a plugin in jquery to do that
https://github.com/niklasvh/jquery.plugin.clipboard
From the project readme
"This script modifies the contents of a selection prior to a copy event being called, resulting in the copied selection being different from what the user selected.
This allows you to append/prepend content to the selection, such as copyright information or other content.
Released under MIT License"
Improving on the answer, restore selection after the alterations to prevent random selections after copy.
function addLink() {
//Get the selected text and append the extra info
var selection = window.getSelection(),
pagelink = '<br /><br /> Read more at: ' + document.location.href,
copytext = selection + pagelink,
newdiv = document.createElement('div');
var range = selection.getRangeAt(0); // edited according to #Vokiel's comment
//hide the newly created container
newdiv.style.position = 'absolute';
newdiv.style.left = '-99999px';
//insert the container, fill it with the extended text, and define the new selection
document.body.appendChild(newdiv);
newdiv.innerHTML = copytext;
selection.selectAllChildren(newdiv);
window.setTimeout(function () {
document.body.removeChild(newdiv);
selection.removeAllRanges();
selection.addRange(range);
}, 100);
}
document.addEventListener('copy', addLink);
Improvement for 2018
document.addEventListener('copy', function (e) {
var selection = window.getSelection();
e.clipboardData.setData('text/plain', $('<div/>').html(selection + "").text() + "\n\n" + 'Source: ' + document.location.href);
e.clipboardData.setData('text/html', selection + '<br /><br />Source');
e.preventDefault();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Example text with <b>bold</b> and <i>italic</i>. Try copying and pasting me into a rich text editor.</p>
Also a little shorter solution:
jQuery( document ).ready( function( $ )
{
function addLink()
{
var sel = window.getSelection();
var pagelink = "<br /><br /> Source: <a href='" + document.location.href + "'>" + document.location.href + "</a><br />© text is here";
var div = $( '<div>', {style: {position: 'absolute', left: '-99999px'}, html: sel + pagelink} );
$( 'body' ).append( div );
sel.selectAllChildren( div[0] );
div.remove();
}
document.oncopy = addLink;
} );
It's a compilation of 2 answers above + compatibility with Microsoft Edge.
I've also added a restore of the original selection at the end, as it is expected by default in any browser.
function addCopyrightInfo() {
//Get the selected text and append the extra info
var selection, selectedNode, html;
if (window.getSelection) {
var selection = window.getSelection();
if (selection.rangeCount) {
selectedNode = selection.getRangeAt(0).startContainer.parentNode;
var container = document.createElement("div");
container.appendChild(selection.getRangeAt(0).cloneContents());
html = container.innerHTML;
}
}
else {
console.debug("The text [selection] not found.")
return;
}
// Save current selection to resore it back later.
var range = selection.getRangeAt(0);
if (!html)
html = '' + selection;
html += "<br/><br/><small><span>Source: </span><a target='_blank' title='" + document.title + "' href='" + document.location.href + "'>" + document.title + "</a></small><br/>";
var newdiv = document.createElement('div');
//hide the newly created container
newdiv.style.position = 'absolute';
newdiv.style.left = '-99999px';
// Insert the container, fill it with the extended text, and define the new selection.
selectedNode.appendChild(newdiv); // *For the Microsoft Edge browser so that the page wouldn't scroll to the bottom.
newdiv.innerHTML = html;
selection.selectAllChildren(newdiv);
window.setTimeout(function () {
selectedNode.removeChild(newdiv);
selection.removeAllRanges();
selection.addRange(range); // Restore original selection.
}, 5); // Timeout is reduced to 10 msc for Microsoft Edge's sake so that it does not blink very noticeably.
}
document.addEventListener('copy', addCopyrightInfo);

Categories