Skip to main content

Copy cell value from IG, revisited

H

How to copy cell value from Interactive Grid? I wrote about this few years back in this article. Since that I have been warned by several people that it does not work on some occasions.


Non editable grid, Redwood theme, read only cell with link... Many issues.

Thanks to Matan from Israel and his ChatGPT friend here is a better solution:

document.addEventListener('copy', (event) => {
    const allowed   = 'a-GV-cell';
    const active_el = document.activeElement;
    if (active_el.closest(`.${allowed.replace(/\s+/g, '.')}`)) {
        const selected = window.getSelection().toString() || active_el.innerText;
        event.clipboardData.setData('text/plain', selected);
        event.preventDefault();
    }
});


But we get the whole row (instead of the selected cell) when copy pasting to Outlook (or any rich text editor).

So after more testing and tweaking, we came up with this final solution:

document.addEventListener('copy', (event) => {
    const allowed   = 'a-GV-cell';
    const active_el = document.activeElement;
    const cell      = active_el.closest(`.${allowed.replace(/\s+/g, '.')}`);
    //
    if (cell && cell.tagName === 'TD') {
        // get selected text
        let selected = window.getSelection().toString().trim();
        if (!selected) {
            // if no text is selected, get only the text nodes directly inside this cell
            selected = $(document.activeElement)[0].innerText;
        }
        if (selected) {
            // copy selected text to the clipboard
            // be aware that navigator works only on https
            //event.clipboardData.setData('text/plain', selected);
            //event.clipboardData.setData('text/html', selected);
            navigator.clipboard.writeText(selected);
            console.log('COPIED', selected);
            event.preventDefault();
        }
    }
});

Note that this still might not work if you are using http instead of https.

Wouldn't it be nice to get this behaviour out of the box?


Comments

Post a Comment