简体   繁体   中英

How would I implement 'copy url to clipboard' from a link or button using javascript or dojo without flash

I got stucked in implementing this feature on my web application. All the other possibilities are mostly by using flash content. Could someone explain how I can achieve it by using plain javascript or by Dojo.

I have been working on the exact same issue for a while. For me flash isn't a viable solution so I came up with this simple work around:

<button onclick="prompt('Press Ctrl + C, then Enter to copy to clipboard','copy me')">Click to Copy</button>

It requires some extra work on the users end but at least it doesn't require flash or external libraries.

example fiddle

I tink this answer is better. There is the way to copy in javascript.

How do I copy to the clipboard in JavaScript?

But if you want to copy URL to clipboard this way work's fine.

function CopyLink() {
            window.clipboardData.setData("Text", location.href);
        }

Html

<a class="" data-toggle="tooltip" data-placement="top" title="Copy profile Link" onclick="copy_to_clipboard('<%=public_profile_url(user.public_id)%>')">
<i class="fa fa-copy"></i>

Css

#url_public_id{
  display: none;
}

JS

function copy_to_clipboard(link) {
    $("#url_public_id").show()
    var Url = document.getElementById("url_public_id");
    Url.select();
    document.execCommand("copy");
    $("#url_public_id").hide()
    alert("Copied URL ");
}

Wanted to implement the same feature. Ended up using https://clipboardjs.com .

new Clipboard('.btn', {
  text: function() {
    return window.location.href;
  }
});

Works well

It has been a long time, but this now works:

document.execCommand('copy');

Which copies the currently selected text to the clipboard. If you want to copy a specific text using javascript, you would have to create a fake input element in the DOM, then do the following

let element = document.getElementById('yourID');
element.value = 'yourText';
element.select();
element.setSelectionRange(0, element.value.length);
document.execCommand('copy');

check my code it's working

static getFileUrl(id){
    var url=new URL("http://localhost:3000/FileUrl")
    url.searchParams.append('id',id)
    return url.href
}
static copyFileUrl(id){
    copy(this.getFileUrl(id))
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM