2

I'm using following JS code to add extra information[LINK] to clipboard while copying the text from website:

        $(document).on('copy', function(e)
        {
            var sel = window.getSelection();
            if(typeof short_url =='undefined'){
                if(window.location.hash=="")
                {
                    var url=document.location.href.split('#')[0];
                }
                else
                {
                    var url=document.location.href;
                }
            }else{
                var url=short_url;
            }
                
            var copyFooter = "<br /><br /><a href='" + url + "'>" + url + "</a>";
            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 the problem is, the text is not copied in exact format(return carriage and line breaks). Instead all text are copied as single line text.

Expected Result: enter image description here

Actual Result: enter image description here

How can the issue be resolved?

Community
  • 1
  • 1
Sujit Baniya
  • 895
  • 9
  • 27

2 Answers2

0

Possibly duplicated from Problem detecting Newlines in JavaScript Range Object ?

Try using sel.toString() if the text is contained in an editable div, or getRangeAt(0) and toString() combined if it's contained in a non editable div.

Community
  • 1
  • 1
namelivia
  • 2,657
  • 1
  • 21
  • 24
0

Using this snippet I could solve the problem:

function getSelectionHtml() {
var html = "";
if (typeof window.getSelection != "undefined") {
    var sel = window.getSelection();
    if (sel.rangeCount) {
        var container = document.createElement("div");
        for (var i = 0, len = sel.rangeCount; i < len; ++i) {
            container.appendChild(sel.getRangeAt(i).cloneContents());
        }
        html = container.innerHTML;
    }
} else if (typeof document.selection != "undefined") {
    if (document.selection.type == "Text") {
        html = document.selection.createRange().htmlText;
    }
}
return html;
}
$(document).on('copy', function(e)
{
   var sel = window.getSelection();
   var copyFooter = "<br /><br /><a href='" + document.location.href + "'>" + document.location.href + "</a><br />";
   var copyHolder = $('<div>', {html: getSelectionHtml()+copyFooter, style: {position: 'absolute', left: '-99999px'}});
   $('body').append(copyHolder);
   sel.selectAllChildren( copyHolder[0] );
   window.setTimeout(function() {
      copyHolder.remove();
   },0);
});
Sujit Baniya
  • 895
  • 9
  • 27