Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I disable Ctrl+A (select all) using jquery in a browser?

Tags:

jquery

I'm trying to prevent information to be copied from a page (for non-technical users of course). I know how to disable selecting text using the mouse. The following jquery code works:

$(function(){
  $.extend($.fn.disableTextSelect = function() {
    return this.each(function(){
      if($.browser.mozilla){//Firefox
        $(this).css('MozUserSelect','none');
      }else if($.browser.msie){//IE
        $(this).bind('selectstart',function(){return false;});
      }else{//Opera, etc.
        $(this).mousedown(function(){return false;});
      });
    });
    $('.noSelect').disableTextSelect();
});

But users can still use Ctrl+A to select the entire page. Any workarounds for this?

like image 790
Keltex Avatar asked Mar 08 '10 18:03

Keltex


4 Answers

this code works for every combination of ctrl+key you want 65 is the ascii code of 'A'

add 97 if you want to check also for 'a'

$(function(){   
    $(document).keydown(function(objEvent) {        
        if (objEvent.ctrlKey) {          
            if (objEvent.keyCode == 65) {                         
                objEvent.disableTextSelect();
                return false;
            }            
        }        
    });
});    

Should works, I wrote it directly without testing..

like image 122
Marcx Avatar answered Oct 21 '22 15:10

Marcx


Works for Windows (Ctrl+A) + MacOS (CMD+A) and use preventDefault() instead of return false:

$(function(){   
  $(document).keydown(function(e) {    
    if ((e.ctrlKey || e.metaKey) && e.keyCode == 65) {
      e.preventDefault();
    }
  });
});
like image 23
ben Avatar answered Oct 21 '22 15:10

ben


Some clients honestly don't understand how the internet works so you should do your part in explaining to them that anything that is displayed to the user can easily be saved, regardless of what you do.

At best, you can disable certain things, making it hard for the simplest of users to copy text.

If you don't do this, someone is going to figure out a way to get by whatever stop-gap you put in place and they will come back to you saying "hey, I thought I told you to lock this down"

like image 38
Allen Rice Avatar answered Oct 21 '22 15:10

Allen Rice


The accepted answer is no more working, because disableTextSelect() was deprecated since jQuery 1.9, and later it was removed and now not supported.

You have to use objEvent.PreventDefault(); - this is working in the newest jQuery and also newest browsers:

$(function() {
    $(document).keydown(function(objEvent) {
        if (objEvent.ctrlKey) {
            if (objEvent.keyCode == 65) {
                objEvent.preventDefault();
            }
        }
    });
});
like image 1
Legionar Avatar answered Oct 21 '22 16:10

Legionar