Raja Raja - 1 month ago 12
Javascript Question

Copy Anchor tag from HTML page to clipboard using Java Script in Chrome browser

I am trying to copy an anchor tag as HTML from web page using JS. The idea is to allow users to copy the anchor element and paste it on word documents as anhcor tag.

HTML code

<div id="dummyDiv" style="position: fixed; opacity: 0;">
<a href="http://localhost/Test">Link to Test</a>
</div>


JS Code

var range = document.createRange();
var selection = window.getSelection();
range.selectNodeContents(document.getElementById('dummyDiv'));
selection.removeAllRanges();
selection.addRange( range );
document.execCommand('copy');


The problem I am facing is this script isn't copying it as anchor element. It only copies the inner text of anchor tag "Link To Test". I am not sure how to get it done. Need some help on this.


The problem seems to be on dev environment which is on VM. the same
code above works fine outside VM on same versioned chrome. Strange why
it isn't working in VM ...

Answer

I use https://clipboardjs.com/ for this.

Thing about clipboard manipulation is: it only works from within a user generated event(click for example). Outside such an event handler, it simply won't put it in the clipboard.

This is my copying code which I use on a click of a button event

 clipboard.copy({ 
            'text/plain':'text',
            'text/html': '<strong>text</strong>'
          }).then(
            function(){
                alert("copied to clipboard");
            },
            function(err){
                window.prompt("Something went wrong with automatically copying the data to clipboard.\nPlease press CTRC + C to copy the data",'text');
          });
Comments