首页 > 解决方案 > dataTables copy to clipboard interference

问题描述

I am using data-tables, client-side processing with the buttons extension.

On the site, I display a table, I need a function to copy some text contained in a div to the clipboard. I am using this code for that purpose:

var div = document.createRange();
div.setStart(container, 0);
div.setEndAfter(container) ;
window.getSelection().addRange(div);
document.execCommand("Copy");

That is all working fine, unless I select an entry in the datatable, before I use my copy to clipboard function. When I select an entry in the table, then use my copy to clipboard-function, it will not only copy the desired text from my container, but also the datatables div content.

I suppose it could be some interference between my js function and the copy to clipboard function of the dataTables button extension, which seem to offer a copy to clipboard function.

Any thoughts on this?

标签: javascriptdatatables

解决方案


Turns out, dataTables creates a range when selecting an entry in a table. So i check if a range already exists, if so - i remove that range and continue with creating my own range.

This works fine for me. Here is the code snippet, if someone is interested:

  s = window.getSelection();
  if(s.rangeCount > 0) {
        for(var i = 0; i < s.rangeCount; i++) {
            s.removeRange(s.getRangeAt(i));
        }
        var div = document.createRange();
        div.setStart(container, 0);
        div.setEndAfter(container) ;
        window.getSelection().addRange(div);
        document.execCommand("Copy");
 }

推荐阅读