Skip to content

Javascript Block Source Code Inspection

Javascript Block Source Code Inspection

You may not want users to look at your html, css, or javascript codes. Hence you are here at this page.

You should take not however that, as html/css/javascript is rendered on the client-side, there is no complete way of blocking the user from viewing your code. You can, however, block out the newbies who are attempting this (which would probably account for over 90% of them). Also, know that blocking source code inspection may mean that your site is less user-friendly and may end up irritating legitimate users.

I have prepared a jsfiddle should you wish to test the code. Now, onto the actual code …

Blocking Right Clicks

To block a specific element (and its children) from being right clickable,

// block a specific element (and all its children) from being right-clicked
// use it like so : disable_rightclick("container_id");
function disable_rightclick(element_id)
{
    var elem = document.getElementById(element_id);
    elem.oncontextmenu = function() {return false;};
}

To block the entire page from being right clickable,

document.oncontextmenu = function() {return false;};

 

Blocking Hotkeys

The commonly used hotkeys for source code inspections are

  • Right Click -> Inspect Element (Hotkey: CTRL + SHIFT + I)
  • Right Click -> View Page Source (Hotkey: CTRL + U)

To block the above hotkeys, put the following codes on your page

document.onkeydown = function(e) {
    if(e.keyCode == 123) {
        return false;
    }
    if(e.ctrlKey && e.shiftKey && e.keyCode == 'I'.charCodeAt(0)){
        return false;
    }
    if(e.ctrlKey && e.shiftKey && e.keyCode == 'J'.charCodeAt(0)){
        return false;
    }
    if(e.ctrlKey && e.keyCode == 'U'.charCodeAt(0)){
        return false;
    }

    if(e.ctrlKey && e.shiftKey && e.keyCode == 'C'.charCodeAt(0)){
        return false;
    }      
}

CONCLUSION

Hopefully with these, you are able to block off users will ill-intent. Do remember that you will be sacrificing usability for security and you should determine for yourself if the trade-off is worth it or not.

Enjoyed the content ? Share it with your friends !
Published inDevelopmentProgramming

Be First to Comment

Leave a Reply

Your email address will not be published.