Web development • Knowledge Base
How to Block Viewing HTML Source
Use practical browser-side deterrents to discourage casual source viewing while keeping sensitive information protected on the server.
01
Understand the limitation
By default, browsers allow users to view HTML source code using “View Page Source” or developer tools. While you cannot 100% prevent determined users from seeing your code, you can discourage casual access.
02
Methods to Block Source Viewing
-
Disable Right Click
Prevent the standard context menu from opening on the page.
document.addEventListener('contextmenu', e => e.preventDefault()); -
Disable Keyboard Shortcuts
Intercept common shortcuts used to open developer tools or save the page source.
document.addEventListener('keydown', function(e) { if (e.ctrlKey && (e.key === 'U' || e.key === 'S') || e.key === 'F12') { e.preventDefault(); alert('This action is disabled!'); } }); -
Obfuscate JavaScript
Convert your JavaScript code into a less readable form using an online obfuscator. Treat obfuscation as a deterrent, not as a way to protect secrets.
03
Full Script Block
Add the script to your HTML head. This combines the right-click and keyboard shortcut deterrents used on this page.
<script>
// ===================== Security Enhancements =====================
// Disable right-click
document.addEventListener('contextmenu', function(e) {
e.preventDefault();
});
// Disable common shortcuts: Ctrl+Shift+I, Ctrl+Shift+J, Ctrl+U, F12
document.addEventListener('keydown', function(e) {
var key = e.key.toUpperCase();
if ((e.ctrlKey && e.shiftKey && (key === 'I' || key === 'J')) ||
(e.ctrlKey && key === 'U') ||
key === 'F12') {
e.preventDefault();
alert('This action is disabled.');
}
});
// Optional: Obfuscated welcome div (Base64)
(function(){
var content = "PGRpdiBzdHlsZT0iZm9udC1zaXplOjIwcHg7Y29sb3I6IzAwMDA7bWFyZ2luOjIwcHg7Ij5XZWxjb21lIHRvIE15IE9iZnVzY2F0ZWQgUGFnZSE8L2Rpdj4=";
/* document.write(atob(content)); */
})();
// Optional: Obfuscated JavaScript example
(function(){
var code = "Y29uc29sZS5sb2coJ0pvYlN0YXJ0ZWQhJyk7";
eval(atob(code));
})();
</script>
Obfuscate JavaScript: Convert your JS code into unreadable form using online obfuscators.
04
Additional Tips
- Always use server-side processing for sensitive data. Client-side code is always visible.
- Combine CSS and JavaScript minification with obfuscation to make code harder to read.
- Remember: These methods are deterrents, not absolute security.