Home > Web Front-end > JS Tutorial > body text

In-depth discussion on JavaScript and JQuery blocking the right-click menu of web pages and prohibiting selection and copying_javascript skills

WBOY
Release: 2016-05-16 16:45:06
Original
1323 people have browsed it

I remember that when I first came into contact with dynamic HTML and JavaScript, I came across script codes about right-click blocking of the mouse. At that time, many of these codes were used to prevent viewers from copying text or other content on the web page without permission. Later, Practical application proves that this approach is not in line with the user experience, and there are many ways to crack it. For example, I once wrote an article explaining how to remove the prohibition of copying on a web page.

It can be seen that it is unwise to restrict right-clicking and copying, but today I still want to talk about prohibiting webpage copying and right-clicking menus, because with the development of webpage APP technology, the difference between webpage applications and desktop applications The boundaries between them are becoming increasingly blurred. Some desktop programs are actually implemented by web pages and JavaScript, and some mobile applications can also be implemented by HTML5 JavaScript. In this case, it is necessary to restrict the right click, because As an APP, the right-click text selection and pop-up menu on the web page are unnecessary in most cases.


The following introduction may only cover a certain aspect of code, but I believe everyone will be able to draw inferences:-)


1. Rough version restricts copying or prohibits right-clicking

Let’s first talk about how to roughly restrict or prohibit viewers from copying text on a web page. To prevent viewers from copying text normally, we must think of disabling certain specific operations of users, such as right-clicking the mouse, selecting, copying, etc. etc., and these operations correspond to corresponding script events. As long as you add a method to these events and let it return false, you can "eat" the operation. Generally, the script code that prohibits copying is as follows:

Copy code The code is as follows:

window.onload = function() {
with(document.body) {
oncontextmenu=function(){return false}
ondragstart=function(){return false}
onselectstart=function(){return false}
onbeforecopy=function(){return false}
onselect=function(){document.selection.empty()}
oncopy=function(){document.selection.empty()}
}
}

Why is this called What about the crude version of the method? Because after using this method to disable the right mouse button, you will find that any control on the web page cannot be right-clicked or selected. The web page seems to have become a rigid picture. Maybe you will feel that it does not matter, but for character input controls such as input and textarea text boxes, it It has a lot to do with it. These places cannot restrict the user's right-click and copy selection operations.

2. Reasonably determine the HTML tag elements to be restricted

How to determine the element tag of the currently processed layer, that is to say, get the HTML Tag where the mouse is currently located. Here we take oncontextmenu as an example. In fact, the function passed in document.body.oncontextmenu has a parameter that we will omit. Yes, the complete writing method should be document.body.oncontextmenu=function(e){} where e is the Event object in JavaScript, which may be obtained through window.event in IE. Through this event object, we can get the HTML Tag where the mouse is when the event is triggered. We can judge whether we want to ignore processing element tags. Here I provide a function as follows:

Copy code The code is as follows:

var isTagName = function(e, whitelists) {
e = e || window.event;
var target = e.target || e.srcElement;
Array.prototype.contains = function(elem)
{
for (var i in this) {
if (this [i] .t stand (). Touppercase () == ELEM.TOSTRING (). TOUPPERCASE ()) Return true;
}
Return false; >                                                                                                                                                                                                                                                        if (whitelists && !whitelists.contains(target.tagName)) {
         return false;


The e here is the event object event, and the target is the element object referenced by the event object. Of course, both variables here are written in a way that is compatible with IE. For details, please refer to "How can I make event.srcElement work in" Firefox and what does it mean?》; The whitelists here are whitelist HTML element tag Tag names, such as ['INPUT', 'TEXTAREA'], which means that the input text box input and textarea will be added to the judgment. If the current event element is Return true, so that we can selectively block the right mouse button through the following code:

Copy the code The code is as follows:

document.body.oncontextmenu=function(e){
return isTagName(e, ['A', 'TEXTAREA']);
}


3. JQuery version’s selective blocking prohibits text selection

Similarly, other operations can also be selectively blocked. In an environment supported by JQuery, I found such an article on StackOverflow "How to disable text selection using jQuery?", although it explains that selection is prohibited. But you can learn from it. The specific code is as follows:

Copy the code The code is as follows:

(function( $){

$.fn.ctrlCmd = function(key) {

var allowDefault = true;

if (!$.isArray(key)) {
Key = [key];
}

return this.keydown(function(e) {
for (var i = 0, l = key.length; i < l; i ) {
           if(e.keyCode === key[i].toUpperCase().charCodeAt(0) && e.metaKey) {
                                                                                                                                                                                                                                              🎜> return allowDefault;
});
};


$.fn.disableSelection = function() {

this.ctrlCmd(['a', 'c ']);

return this.attr('unselectable', 'on')
.css({'-moz-user-select':'-moz-none',
-moz-user-select':'none',
'-o-user-select':'none',
'-khtml-user-select':'none',
'-webkit -User-select ':' None ',
' -MS-User-SELECT ':' None ',
' User-SELECT ':' None '})
.bind (' sexctstart ' false);
};

})(jQuery);

Take the following code to use:


Copy Code The code is as follows:$(':not(input,select,textarea)').disableSelection();

In this way, selection can be prohibited except for input, select, and textarea. The trick of this code is that in addition to selecting start, it also adds some CSS features supported by special browsers to related elements. This can basically realize most browsing At the same time, this code also blocks the keyboard key selection Ctrl A and Ctrl C. I have to admire the author's thoughtful consideration.

4. Further improvement: shielding mouse click operations

A problem I encountered when testing this code is that when clicking on elements other than input, select, and textarea, all pages will be selected. The original author gave a simple method by appending .on('mousedown to the usage code. ', false), thus blocking the mouse click. The usage code becomes as follows:


Copy the code The code is as follows:
$(':not(input,select,textarea)').disableSelection().on('mousedown', false);

But the problem came again. I found that after taking the above code, Input, select, and textarea also started to become abnormal. It seems that the feature of blocking mousedown has been applied to all elements. Now change my thinking and combine the solution I just proposed to judge the event object to achieve selective shielding. I corrected the code as follows:
Copy the code The code is as follows:

$(':not(input,select,textarea)').disableSelection().on('mousedown', function(e) {
var event = $.event.fix(e);
var elem = event.target || e.srcElement;
if (elem.tagName.toUpperCase() != 'TEXTAREA' && elem.tagName.toUpperCase() != 'INPUT') {
e.preventDefault();
return false;
}
return true;
});

This way textarea and input are not Mousedown will be restricted. We extract this code into a function:
Copy the code The code is as follows:

function jQuery_isTagName(e, whitelists) {
e = $.event.fix(e);
var target = e.target || e.srcElement;
if (whitelists && $.inArray( target.tagName.toString().toUpperCase(), whitelists) == -1) {
                 return false; not(input,select,textarea)').disableSelection().on('mousedown', function(e) {
if (!jQuery_isTagName(e, ['INPUT', 'TEXTAREA'])) {
e.preventDefault();
return false;
}
return true;
});



5. JQuery version’s selective blocking prohibits the right mouse button
For the right-click menu, we can handle it like this:

Copy the code

The code is as follows: $(document).bind("contextmenu",function(e){ if (!jQuery_isTagName(e, ['INPUT', 'TEXTAREA'])) { e.preventDefault();
return false;
}
return true;
});

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template