Raja Raja - 1 year ago 137
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>

JS Code

var range = document.createRange();
var selection = window.getSelection();
selection.addRange( range );

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 Source

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

            'text/html': '<strong>text</strong>'
                alert("copied to clipboard");
                window.prompt("Something went wrong with automatically copying the data to clipboard.\nPlease press CTRC + C to copy the data",'text');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download