Leonardo Buzinskas
Leonardo Buzinskas

Reputation: 33

JavaScript - Copy HUGE string to clipboard

I'm developing a grid and now I'm trying to copy information from the grid to Excel. Everything works as expected, but if the data is too big, the copy process takes a long time.

I'm using the textarea trick, with "document.execCommand("copy")".

I could see that my problem is here "textarea.select();" Pasting the text in the textarea is very fast, but it takes a looooong time to select all the text. After that is also quick to send to the clipboard. The problem seems to be the select.

I'm talking about copying arrays like [500000, 40]. A lot of data.

I've tried some Chrome API, but couldn't find any good solution by the end. Is there any other clever way to copy data to the clipboard?

Upvotes: 3

Views: 2593

Answers (1)

VeerJain89
VeerJain89

Reputation: 141

The problem is the time taken by data processing is longer than the execCommand("copy").

Actually copy requires to be called in user generated event and there is a time limit attached to it(there is no mention anywhere but with my work I found it to be ~5 secs, any specification on this will be welcomed). If your data processing needs more than this it will not copy the data. One solution to this is to get the data processed in advance and then open dialog/popup to ask the user to click button to copy the data.

Further for a fast copy (doesn't work in safari) you can use below method:

var contentToCopy;
function copyDataToClipboard(e) {
    e.preventDefault(); // default behaviour is to copy any selected text
    e.clipboardData.setData("text/plain", contentToCopy);
}
function copy(content) {
    contentToCopy = content;
    document.addEventListener("copy", copyDataToClipboard);
    try {
        document.execCommand("copy");
    } catch (exception) {
        console.error("Copy to clipboard failed");
    } finally {
        document.removeEventListener("copy", copyDataToClipboard);
    }
}

copy(content = [Any content you would like to copy to clipboard]);

Hope this will resolve your issues related to copying large data.

Upvotes: 6

Related Questions