preface

Sometimes we often come across these scenes: playing nuggets, zhihu copy a paragraph of text, always add some copyright information at the back of the content, as well as novel websites, there are forbidden to select, forbidden to copy this function, and click the automatic copy account function.

I often encounter these scenes, and sometimes I would think about how to do it. I studied them in my spare time at the weekend, and then found that all of them are related to the operation of the clipboard, and they are not difficult. After knowing about them, I know how to do them, so I will sort out and share a wave with you.

Personal blog: obkoro1.com


Directory:

  • The API is introduced
  • Implement class zhihu/nuggets copy a large section of text to add copyright information
  • Realizes the anti-copy function of class starting point network
  • Crack anti-copy
  • Click copy

The API is introduced:

Copy, cut, paste events:

  1. copyTriggered when a replication operation occurs;
  2. cutTriggered when shearing operation occurs;
  3. pasteTriggered when the paste operation occurs;
  4. Each event corresponds to a before event:beforecopy,beforecut,beforepaste;

These “before” s are not often used, so we’ll just focus on the other three.

Triggering conditions:

  1. Right-click menu copy, paste, cut;

  2. Corresponding keyboard combinations are used, such as command+ C, command+ V;

    Even if you press it randomly, it will trigger the event. In Chrome, Firefox, and Safari, these before events are triggered only when a clipboard event is actually happening. In IE, before events are triggered. When I actually tested the latest version of Chorme, it also triggered random press, so the limitation should be on earlier versions.

    Paste: copy, cut, paste: before: copy, cut, paste

Use posture:

Take copy as an example:

Document. Body. Oncopy = e = > {/ / do something to monitor global copy} / / in this writing: the document. The addEventListener (" copy ", e = > {/ / do something to monitor global copy});Copy the code

The above is listened for globally on document.body, but what many people don’t know is that we can also add clipboard events to some DOM individually:

<div >< div id="test2"></div> Test1. oncopy = e => {// Listen for replication events on test1 to do something // Replication events on test1 will trigger callbacks, not elsewhere}Copy the code

The same is true of other events, which I will not repeat here.

ClipboardData object: Used to access and modify data in the clipboard

Compatible with:

In Internet Explorer, this object is a property of the Window object. In Chrome, Safari, and Firefox, this object is a property of the corresponding Event object. So when we use it, we need to do the following compatibility:

document.body.oncopy = e => { let clipboardData = (e.clipboardData || window.clipboardData); // Get clipboardData object + do something}Copy the code

Object methods:

The object has three methods: getData(), setData(), and clearData()

  • GetData () accesses the data in the clipboard

    Arguments: getData() takes a ‘text’ argument, which is the format of the data to fetch.

    In copying, cutting, and pasting triggered event data:

    Paste (); getData(); paste (); getData();

    Data to paste:

    document.body.onpaste = e => { let clipboardData = (e.clipboardData || window.clipboardData); // Compatible handling console.log(' data to paste ', clipboarddata.getData ('text')); }Copy the code

    Data copied/cut:

    The data in copy and clipping needs to be accessed via window.getSelection(0).toString() :

    Document.body.oncopy = e => {console.log(' Copied data :', window.getSelection(0).toString()); }Copy the code
  • SetData (): Modifies data in the clipboard

    Arguments: The first argument is also ‘text’ and the second argument is the text to be placed in the clipboard.

    The rest is left in the following copy zhihu/nuggets copy a large section of text to add copyright information there again.

  • clearData() :

    This method is not quite know, try for a long time do not know how to use (if there is a big guy know, can point out in the comment area).

    If you just want to stop copying, or stop pasting, there are other ways to do it, and you can fine-grained it.


Application:

If learning is not about installing X, then nothing will matter. Let’s see where this thing can be used:

Copy a large section of text to add copyright information:

The implementation is simple: after the default replication is disabled, the main thing is to add information to the copied content and then write the information to the clipboard according to the setData() method of clipboardData.

You can just copy this code and try it locally.

// This is not a global listener, it should only listen to the dom scope of the article. document.body.oncopy = event => { event.preventDefault(); // Cancel the default copy event let textFont, copyFont = window.getSelection(0).toString(); If (copyFont. Length > 10) {textFont = copyFont + '\n' + 'author: OBKoro1 \ n '+' links: https://juejin.cn/user/78820536236951\n '+' source: the nuggets' \ n '+' copyright owned by the author. Commercial reprint please contact the author for authorization, non-commercial reprint please indicate the source. '; } else { textFont = copyFont; If no more than 10 words are used, the content is copied. } if (event.clipboardData) { return event.clipboardData.setData('text', textFont); / / to write information into the clipboard} else {/ / compatible with IE return window. ClipboardData. SetData (" text ", textFont); }}Copy the code

Command +c, command+v

You copy the content Source: author: OBKoro1 links: https://juejin.cn/user/78820536236951 the nuggets copyright owned by the author. Commercial reprint please contact the author for authorization, non-commercial reprint please indicate the source.Copy the code

To achieve the anti-copy function of the starting point network:

  • Disable copy and cut
  • Disable right-click, right-click some options: select all, copy, paste, etc.
  • Disable text selection, can select but can not copy, poor experience.
  • User-select disables text selection with CSS.

You can copy the code locally and play with it:

/ / prohibited right-click menu document. Body. Oncontextmenu = e = > {the console. The log (e, 'right-click'); return false; // e.preventDefault(); }; // Disable text selection. Document. The body. The onselectstart = e = > {the console. The log (e, 'text choose'); return false; // e.preventDefault(); }; Document.body. onCopy = e => {console.log(e, 'copy'); return false; // e.preventDefault(); } // Disallow cutting document.body.oncut = e => {console.log(e, 'cut'); return false; // e.preventDefault(); }; Paste => {console.log(e, 'paste'); return false; // e.preventDefault(); }; // CSS disallows text selection without triggering js body {user-select: none; -moz-user-select: none; -webkit-user-select: none; -ms-user-select: none; }Copy the code

PS:

  • usee.preventDefault()It can also be disabled, but is recommendedreturn falseSo you don’t have to visiteandeThe method of.
  • In the sampledocument.bodyIt is disabled globally, but you can also disable dom(certain areas).

Crack anti-copy:

The above anti-copy method is implemented through JS + CSS, so the idea is: disable JS + disable user-select style.

For Chrome: Open the browser console, press F1 to enter Setting, and check Disable JavaScript.

At this point, if you can’t copy it, go to the user-select style and cancel it.

So those pirated novels by hand, I really don’t understand, Excuse me??

Click the Copy function:

ClipboardData cannot be used:

In IE can use window. ClipboardData. SetData (‘ text ‘, ‘content’).

As mentioned earlier, clipboardData is a window property in IE.

Other browsers are properties of the corresponding Event object, which is actually a security measure to prevent unauthorized access, so we can’t do this with clipboardData for compatibility with other browsers.

Specific practices:

  • Create a hidden input box

  • When clicked, the content to be copied is placed in the Input box

  • Select text input.select()

    Only input or Textarea can be used to select text.

  • Document. execCommand(“copy”), to execute the browser copy command.

    function copyText() { var text = document.getElementById("text").innerText; Var input = document.getelementById ("input"); // Get dom input.value = text; // Modify the contents of the text box input.select(); // Select the text document.execCommand("copy"); // Execute the browser copy command alert(" copy succeeded "); }Copy the code

Click on the demo of the copy and it’s here, so you can click on it.


conclusion

It’s fun to learn about these things outside of work, and it can broaden your knowledge.

In fact, as long as we listen for these events, we can perform various operations on the content to be cut, such as changing the text when copying, looking for images when pasting, or cutting the length of the text, etc., which only limits you

I hope the friends can click like/follow, your support is the biggest encouragement to me.

Blog, front-end accumulation of documents, public account, GitHub, Wx :OBkoro1, email: [email protected]

The above 2018.8.8

References:

Js elevation 14.2.2 Operating clipboard

How to prohibit copy and paste on the web page and how to crack

Native JS implements the click of a button to copy text