getSelection removes links from selection?

313 Views Asked by At

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 &copy; 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>
1

There are 1 best solutions below

0
On

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.