B
B
BoriHagen2021-05-26 14:40:16
JavaScript
BoriHagen, 2021-05-26 14:40:16

Is there a cross-browser option to copy text to the clipboard?

I'm trying to find a solution to copy text to clipboard that works for all browsers. If not, then you need a variant supported in most browsers. Tried to use navigator.clipboard.writetext, but it only works on https connection. I work for http. There is also an IE-only option - document.execCommand("copy");. I would like to know if there are any other options?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
vsvasya, 2021-05-26
@BoriHagen

function copyToClipboard(value) {
    var prev_focus = document.activeElement;
    var area = document.createElement('textarea');
    area.value = value;
    document.body.appendChild(area);
    area.focus();
    area.select();
    area.setSelectionRange(0, 99999); /* For mobile devices */
    document.execCommand('copy');
    document.body.removeChild(area);
    if (prev_focus) {
        prev_focus.focus();
    }
}

Works everywhere - Firefox, Chrome, Safari

N
Nikita Nikonov, 2021-05-28
@RickCastle2018

I recommend https://clipboardjs.com/
With this library you don't have to worry about https and Internet Explorer

P
profesor08, 2021-05-26
@profesor08

I work for http

Work on https, or document.execCommand("copy")on selected text.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question