In-depth exploration of JavaScript and JQuery webpage shielding right-click menu and prohibit selection of copy_javascript skills

Source: Internet
Author: User
This article mainly introduces how JavaScript and JQuery shield webpage right-click menu and prohibit copy selection, for more information, see. I remember that when I first came into contact with dynamic HTML and JavaScript, I got in touch with the script code for right-click shielding, at that time, many of these codes were used to prevent the viewer from copying text or other content on the webpage without permission. Later practical applications proved that this practice was not in line with the user experience, there are also a lot of methods to crack. For example, I once wrote an article to explain how to remove the method of prohibiting the copy on the webpage.

It can be seen that it is unwise to restrict right-click and copy, but today I still want to talk about prohibiting webpage copy and right-click menu, because with the development of web APP technology, the boundaries between web applications and desktop applications are becoming increasingly blurred. Some desktop applications are actually implemented by the combination of web pages and JavaScript. Other mobile apps can also be implemented by HTML5 + JavaScript, in this case, right-click restriction is necessary, because as an APP, right-click selection of text and pop-up menus on a webpage is unnecessary in most cases.


The subsequent introduction may only contain some code, but I believe you will be able to draw a line from the following :-)


1. Select copy or prohibit right-clicking for rough version restrictions

First, let's talk about how to restrict or prohibit the viewer from copying the text on the webpage and prevent the viewer from copying the text normally. We certainly want to disable some specific operations of the user, such as right-clicking, select, copy, and so on. These operations correspond to the corresponding script events. You only need to add a method to these events so that it can "eat" the operation if it returns false, generally, the script code that prohibits replication is as follows:

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 method a rough version? If you use this method to prohibit right-clicking, you will find that no widget on the webpage can be right-clicked or selected. The webpage seems to be a rigid image, and you may feel indifferent, however, the character input controls such as input and textarea text boxes have a great relationship. The right-click and select copy operations cannot be restricted in these areas.

Ii. Reasonably Determine the HTML Tag elements to be restricted

How can we determine the element Tag of the currently processed layer? That is to say, we can get the HTML Tag of the current mouse. Here we take oncontextmenu as an example. body. the oncontextmenu passed in function has a parameter which we omitted. The complete syntax should be document. body. oncontextmenu = function (e) {} Here e is the Event object in JavaScript. in IE, it may be through window. event. This event object can be used to obtain the HTML Tag of the mouse when the event is triggered. We can determine if we want to ignore the Tag of the processing element. Here I provide a function as follows:

The Code is as follows:


Var isTagName = function (e, whitelists ){
E = e | window. event;
Var target = e.tar get | e. srcElement;
Array. prototype. contains = function (elem)
{
For (var I in this)
{
If (this [I]. toString (). toUpperCase () = elem. toString (). toUpperCase () return true;
}
Return false;
}
If (whitelists &&! Whitelists. contains (target. tagName )){
Return false;
}
Return true;
};


Here e is the event object event, and target is the Element Object referenced by the event object. Of course, both variables adopt the IE-compatible method. For details, see How can I make event. srcElement work in Firefox and what does it mean? "; Here, whitelists is the Tag Name of the HTML element in the whitelist, for example, ['input', 'textarea '], which indicates that the INPUT text box input and TEXTAREA are added for judgment, if the current event element is, true is returned. In this way, the following code can selectively block the right mouse button:

The Code is as follows:


Document. body. oncontextmenu = function (e ){
Return isTagName (e, ['A', 'textarea ']);
}


Iii. JQuery edition selective blocking and Text Selection prohibited

Other operations can also be selectively shielded. In the environments supported by JQuery, I found this article "How to disable text selection using jQuery?" In StackOverflow. Although the selection is not allowed, the specific code is as follows:

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 ){
AllowDefault = false;
}
};
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 ('selectstart', false );
};

}) (JQuery );


Use the following code:

The Code is as follows:


$ (': Not (input, select, textarea)'). disableSelection ();

In this way, you can disable selection except input, select, and textarea. the skill of this Code is to add some CSS features supported by special browsers to relevant elements in addition to selectstart, in this way, most browsers can be compatible. At the same time, this code also shields the selection of Ctrl + A and Ctrl + C on the keyboard keys, so I have to admire the thoughtful consideration of the author.

Iv. Further Improvement: shielding mouse clicks

When testing this code, I encountered a problem that all the elements except input, select, and textarea were selected on the page. The author of the original article provided a simple method to append the code. on ('mouseunder', false), this shields the mouse clicking and changes the code to the following:

The Code is as follows:

$ (': Not (input, select, textarea)'). disableSelection (). on ('mousedown ', false );


But again, I found that after taking the above Code, the input, select, and textarea also began to become abnormal. It seems that the mousedown feature is blocked and applied to all elements. Now I want to change my mind and combine the scheme I just proposed to determine the event object to implement selective blocking. I will correct the Code as follows:

The Code is as follows:


$ (': Not (input, select, textarea)'). disableSelection (). on ('mousedown ', function (e ){
Var event = $. event. fix (e );
Var elem = event.tar get | e. srcElement;
If (elem. tagName. toUpperCase ()! = 'Textaga' & elem. tagName. toUpperCase ()! = 'Input '){
E. preventDefault ();
Return false;
}
Return true;
});


In this way, textarea and input will not limit mousedown. We will extract this code as a function:

The Code is as follows:


Function jQuery_isTagName (e, whitelists ){
E = $. event. fix (e );
Var target = e.tar get | e. srcElement;
If (whitelists & $. inArray (target. tagName. toString (). toUpperCase (), whitelists) =-1 ){
Return false;
}
Return true;
}

$ (': Not (input, select, textarea)'). disableSelection (). on ('mousedown ', function (e ){
If (! JQuery_isTagName (e, ['input', 'textarea ']) {
E. preventDefault ();
Return false;
}
Return true;
});

5. Select and disable right-click for JQuery

For the right-click menu, we can handle it like this:

The Code is as follows:


$ (Document). bind ("contextmenu", function (e ){
If (! JQuery_isTagName (e, ['input', 'textarea ']) {
E. preventDefault ();
Return false;
}
Return true;
});

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.