This is the sixth day of my participation in Gwen Challenge

In order to protect page content, or to induce users to register, websites often need to implement functions that prohibit users from copying and cutting page content, or allow users to copy and cut page content after logging in. We respectively from JavaScript, CSS, HTML tag attributes three aspects to see how to achieve the effect of web page copy prohibition.

Implemented in JavaScript

Prohibit the page copy, the most direct idea is to copy the page event and cut the event to rewrite. In addition, we can do this by disabling the right mouse button menu events and preventing the user from selecting content. The relevant code is as follows:

// Disable right-click menus
document.oncontextmenu = function(){ return false; };
// Disable text selection
document.onselectstart = function(){ return false; };
// Disable replication
document.oncopy = function(){ return false; };
// Forbid clipping
document.oncut = function(){ return false; };
Copy the code

Through HTML tag attributes

In addition to JS code, you can also directly disable page copying and cutting by setting tag attributes, as shown below:

<body oncopy="return false" oncut="return false;" onselectstart="return false" oncontextmenu="return false">
<! -... -->
</body>
Copy the code

This method is essentially the same as the JS implementation. When the page replication function needs to be restored (for example, after judging that the user has registered and logged in), you need to use JS code to copy and cut the page and select the content to restore the function, the code is as follows:

document.body.oncopy = null;
document.body.oncut = null;
document.body.onselectstart = null;
document.body.oncontextmenu = null;
Copy the code

Using CSS

We can also limit copying by using CSS styles to prevent page content from being selected. The style code is as follows:

body {
  -moz-user-select:none; /* Firefox private properties */
  -webkit-user-select:none; /* WebKit kernel private attributes */
  -ms-user-select:none; /* IE private attributes (IE10 and later) */
  -khtml-user-select:none; /* KHTML kernel private attribute */
  -o-user-select:none; /* Opera private properties */
  user-select:none; /* CSS3 attributes */
}
Copy the code

To restore the page content selection function, you need to modify the JS code label style to achieve, the code is as follows:

document.body.style.webkitUserSelect = 'auto'; // Firefox
document.body.style.userSelect = 'auto'; // Chrome
/ /...
Copy the code