How to prevent the contents of an element from being copied after Ctrl+A and Ctrl+C?

Asked

Viewed 297 times

6

I have a page and want to allow the copy normally, but I wish specific elements were not copied after using Ctrl+To and Ctrl+C, for example forms, navigation menus and advertising banners.

This is because the content is usually what matters if someone wants to copy, but the navbar is not interesting.

I tried this:

form, nav {
    -webkit-user-select: none;
       -moz-user-select: none;
        -ms-user-select: none;
  -webkit-touch-callout: none;
            user-select: none;
}

But if I push Ctrl+To and Ctrl+C the forms and the navbar are copied together anyway.

Is there any way to prevent the copying of specific elements after the use of Ctrl+To?

1 answer

4


After a few tests, I found solutions with :before {} and content: ""; CSS, but this only works for simple text, so I decided to test the event oncopy javascript.

I got it this way, using the events copy, beforecopy, the property display: none and document.querySelectorAll to get the elements (no need to put in the onload).

Support

  • Firefox
  • Chrome
  • Internet Explorer 10+

Sample code

(function (d) {
    if (d.addEventListener && d.querySelectorAll) {
        //Edite esta variável conforme a necessidade (elementos que deseja impedir que sejam copiados)
        var query = "nav, form";

        //Nota: no IE a tag script é copiada, então prefira deixar sempre ele
        query += ", script";

        var running = false;

        function finishEventCopy() {
            running = false;
        }

        //Oculta os elementos pra não serem copiados
        function preventEventCopy(e) {
            if (running) return;

            running = true;

            //Clona o body
            var cloned = document.body.cloneNode(true);

            //Cria elemento temporário que será selecionado pelo range
            var tmpNode = document.createElement("div");
            var els = cloned.querySelectorAll(query);

            for (i = 0, j = els.length; i < j; i++) {
                els[i].parentNode.removeChild(els[i]);
            }

            //Cria um elemento vazio pra ajustar o range de maneira mais fácil
            var empty = document.createElement("div");
            empty.innerHTML = " ";

            tmpNode.appendChild(cloned);
            tmpNode.appendChild(empty);

            document.body.appendChild(tmpNode);

            //define o range no DIV temporário
            var range = document.createRange();
            range.setStart(tmpNode.firstChild, 0);
            range.setEnd(empty, 1);

            //Seleciona o div temporário
            var sel = window.getSelection();
            sel.removeAllRanges();
            sel.addRange(range);

            //Executa o comando de cópia
            document.execCommand("copy");

            document.body.removeChild(tmpNode);

            empty = range = sel = tmpNode = null;

            setTimeout(finishEventCopy, 10);
        }

        function triggerByKeyboard(e) {
            if (e.ctrlKey && e.keyCode == 67) preventEventCopy(e);
        }

        d.addEventListener("beforecopy", preventEventCopy, false);
        d.addEventListener("copy", preventEventCopy, false);
        d.addEventListener("keydown", triggerByKeyboard, false);
    }
})(document);
<nav>
Navegação
</nav>

<div class="container">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut porttitor orci at purus elementum feugiat. Ut sed ipsum tempor, consequat tortor in, egestas metus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. In viverra volutpat tellus ullamcorper condimentum. In pharetra mauris vel neque congue consectetur. Maecenas semper accumsan dictum. Nam augue lectus, consequat ut sapien id, sollicitudin auctor sapien. Curabitur libero sapien, egestas eu mauris ut, aliquet pharetra orci. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam sapien tortor, viverra eget leo vel, pellentesque iaculis velit. Praesent vehicula, erat sit amet fermentum scelerisque, justo lorem gravida orci, ut euismod nisi nibh a dolor. Mauris in pellentesque sapien. Sed lobortis magna quam, in sodales ante pulvinar et. Pellentesque et rhoncus orci, in blandit elit.
</div>

<form>
Formulário
</form>


Disabling copy of entire page

Maybe if you have the need to prevent full copying you can use something like:

function blockCopy(e) {
    e.preventDefault();
    e.stopPropagation();
}

function blockPressCtrlC(e) {
    if (e.ctrlKey && e.keyCode == 67) {
        blockCopy(e);
    }
}

document.addEventListener("copy", blockCopy, false);
document.addEventListener("beforecopy", blockCopy, false);

document.addEventListener("keydown", blockPressCtrlC, false);

But note this nay is foolproof, only makes it difficult to copy the content, but it is still possible to cheat.


One answer related to this that may be useful is:

  • The simple fact of the element is with display:none; makes it not be copied? oo

  • Anonymity function in addEventListener? I want to see you cancel this after :D

  • @Does Guilhermelautert mean to remove the event? But it has some goal to remove it?

  • That depends on your need, I was just kidding.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.