disable-right-click
v1.0.1
Published
Lightweight, zero-dependency JavaScript library to disable the browser right-click (context menu) globally or on specific elements
Maintainers
Readme
disable-right-click
Comprehensive, modular JavaScript library for content protection. Disable right-click, keyboard shortcuts, text selection, drag-drop, developer tools, print, clipboard operations, and more. Fully modular - use only what you need.
✨ Features
Core Protection Modules
- Right-Click Protection - Disable context menu globally or on specific elements
- Keyboard Shortcuts Protection - Block copy, paste, save, print, F12, and custom shortcuts
- Text Selection Protection - Prevent text selection via mouse or keyboard
- Drag & Drop Protection - Prevent dragging images and content
- Developer Tools Protection - Detect and handle DevTools opening
- Print Protection - Block print dialog and print operations
- Clipboard Protection - Monitor and block copy/paste operations
- Image Protection - Protect images with overlays and watermarks
- Screenshot Protection - Detect screenshot attempts (limited effectiveness)
- Frame Busting - Prevent iframe embedding
- View Source Protection - Block view source (Ctrl+U)
- Download Protection - Block download operations
Key Benefits
- Modular Architecture - Enable only the modules you need
- Flexible Configuration - Per-module, per-selector control
- Event-Driven - Listen to all protection events
- TypeScript Support - Full type safety
- Zero Dependencies - Lightweight and fast
- Cross-Browser - Works in all modern browsers
- Granular Control - Per-element, per-page, per-module
⚠️ Important: This library is a deterrent, not a security solution. Determined users can still access content through browser DevTools, network inspection, or other methods. Use for content protection, not security.
📦 Installation
npm / yarn / pnpm
npm install disable-right-clickor
yarn add disable-right-clickor
pnpm add disable-right-clickCDN (ESM Module)
Regular Version
<!-- jsDelivr -->
<script type="module">
import ContentProtection from 'https://cdn.jsdelivr.net/npm/disable-right-click@latest/dist/index.mjs';
const protection = new ContentProtection({
modules: {
rightClick: { enabled: true },
keyboardShortcuts: { enabled: true }
}
});
</script><!-- unpkg -->
<script type="module">
import ContentProtection from 'https://unpkg.com/disable-right-click@latest/dist/index.mjs';
const protection = new ContentProtection({
modules: {
rightClick: { enabled: true }
}
});
</script>Minified Version (Recommended for Production)
<!-- jsDelivr - Minified -->
<script type="module">
import ContentProtection from 'https://cdn.jsdelivr.net/npm/disable-right-click@latest/dist/index.min.mjs';
const protection = new ContentProtection({
modules: {
rightClick: { enabled: true },
keyboardShortcuts: { enabled: true }
}
});
</script><!-- unpkg - Minified -->
<script type="module">
import ContentProtection from 'https://unpkg.com/disable-right-click@latest/dist/index.min.mjs';
const protection = new ContentProtection({
modules: {
rightClick: { enabled: true }
}
});
</script>CDN (CommonJS - for Node.js environments)
Regular Version
<!-- jsDelivr -->
<script src="https://cdn.jsdelivr.net/npm/disable-right-click@latest/dist/index.js"></script>
<script>
// Available as window.ContentProtection (if UMD build exists)
// Or use require in Node.js
const ContentProtection = require('disable-right-click');
</script>Minified Version (Recommended for Production)
<!-- jsDelivr - Minified -->
<script src="https://cdn.jsdelivr.net/npm/disable-right-click@latest/dist/index.min.js"></script>
<script>
// Available as window.ContentProtection (if UMD build exists)
// Or use require in Node.js
const ContentProtection = require('disable-right-click');
</script>🚀 Quick Start
Basic Usage (All Modules)
import ContentProtection from 'disable-right-click';
const protection = new ContentProtection({
modules: {
rightClick: { enabled: true },
keyboardShortcuts: { enabled: true },
textSelection: { enabled: true }
}
});📖 Usage Examples
HTML / Vanilla JavaScript
Using npm (with bundler)
<!DOCTYPE html>
<html>
<head>
<title>Content Protection Example</title>
</head>
<body>
<div id="app">
<h1>Protected Content</h1>
<p>Try right-clicking, selecting text, or using Ctrl+C</p>
<img src="image.jpg" alt="Protected Image">
</div>
<script type="module">
import ContentProtection from './node_modules/disable-right-click/dist/index.mjs';
const protection = new ContentProtection({
modules: {
rightClick: { enabled: true },
keyboardShortcuts: { enabled: true },
textSelection: { enabled: true },
dragDrop: { enabled: true },
image: { enabled: true, watermark: true }
}
});
</script>
</body>
</html>Using CDN
<!DOCTYPE html>
<html>
<head>
<title>Content Protection Example</title>
</head>
<body>
<div id="app">
<h1>Protected Content</h1>
<p>Try right-clicking, selecting text, or using Ctrl+C</p>
</div>
<script type="module">
import ContentProtection from 'https://cdn.jsdelivr.net/npm/disable-right-click@latest/dist/index.min.mjs';
const protection = new ContentProtection({
modules: {
rightClick: { enabled: true },
keyboardShortcuts: { enabled: true },
textSelection: { enabled: true }
}
});
</script>
</body>
</html>React
Installation
npm install disable-right-clickUsage in React Component
import React, { useEffect, useRef } from 'react';
import ContentProtection from 'disable-right-click';
function ProtectedPage() {
const protectionRef = useRef(null);
useEffect(() => {
// Initialize protection
protectionRef.current = new ContentProtection({
modules: {
rightClick: { enabled: true },
keyboardShortcuts: { enabled: true },
textSelection: { enabled: true },
dragDrop: { enabled: true }
}
});
// Cleanup on unmount
return () => {
if (protectionRef.current) {
protectionRef.current.destroy();
}
};
}, []);
const toggleProtection = () => {
if (protectionRef.current) {
const isEnabled = protectionRef.current.isModuleEnabled('rightClick');
if (isEnabled) {
protectionRef.current.disableModule('rightClick');
} else {
protectionRef.current.enableModule('rightClick');
}
}
};
return (
<div>
<h1>Protected Content</h1>
<button onClick={toggleProtection}>Toggle Protection</button>
<p>Try right-clicking or selecting text</p>
</div>
);
}
export default ProtectedPage;Using React Hook
import React, { useEffect, useRef } from 'react';
import ContentProtection from 'disable-right-click';
function useContentProtection(options) {
const protectionRef = useRef(null);
useEffect(() => {
protectionRef.current = new ContentProtection(options);
return () => {
if (protectionRef.current) {
protectionRef.current.destroy();
}
};
}, []);
return protectionRef.current;
}
function App() {
const protection = useContentProtection({
modules: {
rightClick: { enabled: true },
keyboardShortcuts: { enabled: true }
}
});
return <div>Protected Content</div>;
}Vue.js
Installation
npm install disable-right-clickUsage in Vue Component
<template>
<div>
<h1>Protected Content</h1>
<button @click="toggleProtection">
{{ isProtected ? 'Disable' : 'Enable' }} Protection
</button>
<p>Try right-clicking or selecting text</p>
</div>
</template>
<script>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import ContentProtection from 'disable-right-click';
export default {
name: 'ProtectedPage',
setup() {
const protection = ref(null);
const isProtected = ref(false);
onMounted(() => {
protection.value = new ContentProtection({
modules: {
rightClick: { enabled: true },
keyboardShortcuts: { enabled: true },
textSelection: { enabled: true },
dragDrop: { enabled: true }
}
});
isProtected.value = true;
});
onBeforeUnmount(() => {
if (protection.value) {
protection.value.destroy();
}
});
const toggleProtection = () => {
if (protection.value) {
if (isProtected.value) {
protection.value.disableAll();
isProtected.value = false;
} else {
protection.value.enableAll();
isProtected.value = true;
}
}
};
return {
isProtected,
toggleProtection
};
}
};
</script>Using Vue Plugin
// plugins/contentProtection.js
import ContentProtection from 'disable-right-click';
export default {
install(app, options) {
const protection = new ContentProtection(options);
app.config.globalProperties.$contentProtection = protection;
app.provide('contentProtection', protection);
}
};
// main.js
import { createApp } from 'vue';
import App from './App.vue';
import ContentProtection from './plugins/contentProtection';
const app = createApp(App);
app.use(ContentProtection, {
modules: {
rightClick: { enabled: true },
keyboardShortcuts: { enabled: true }
}
});
app.mount('#app');Angular
Installation
npm install disable-right-clickUsage in Angular Component
import { Component, OnInit, OnDestroy } from '@angular/core';
import ContentProtection from 'disable-right-click';
@Component({
selector: 'app-protected',
template: `
<div>
<h1>Protected Content</h1>
<button (click)="toggleProtection()">
{{ isProtected ? 'Disable' : 'Enable' }} Protection
</button>
<p>Try right-clicking or selecting text</p>
</div>
`
})
export class ProtectedComponent implements OnInit, OnDestroy {
private protection: ContentProtection | null = null;
isProtected = false;
ngOnInit() {
this.protection = new ContentProtection({
modules: {
rightClick: { enabled: true },
keyboardShortcuts: { enabled: true },
textSelection: { enabled: true },
dragDrop: { enabled: true }
}
});
this.isProtected = true;
}
ngOnDestroy() {
if (this.protection) {
this.protection.destroy();
}
}
toggleProtection() {
if (this.protection) {
if (this.isProtected) {
this.protection.disableAll();
this.isProtected = false;
} else {
this.protection.enableAll();
this.isProtected = true;
}
}
}
}Using Angular Service
// services/content-protection.service.ts
import { Injectable } from '@angular/core';
import ContentProtection from 'disable-right-click';
@Injectable({
providedIn: 'root'
})
export class ContentProtectionService {
private protection: ContentProtection | null = null;
initialize(options: any) {
if (!this.protection) {
this.protection = new ContentProtection(options);
}
return this.protection;
}
getProtection() {
return this.protection;
}
destroy() {
if (this.protection) {
this.protection.destroy();
this.protection = null;
}
}
}
// component.ts
import { Component, OnInit } from '@angular/core';
import { ContentProtectionService } from './services/content-protection.service';
@Component({
selector: 'app-root',
template: '<div>Protected Content</div>'
})
export class AppComponent implements OnInit {
constructor(private protectionService: ContentProtectionService) {}
ngOnInit() {
this.protectionService.initialize({
modules: {
rightClick: { enabled: true },
keyboardShortcuts: { enabled: true }
}
});
}
}Next.js
Installation
npm install disable-right-clickUsage in Next.js Component
// pages/protected.js or app/protected/page.js
import { useEffect, useRef } from 'react';
import ContentProtection from 'disable-right-click';
export default function ProtectedPage() {
const protectionRef = useRef(null);
useEffect(() => {
// Only run on client side
if (typeof window !== 'undefined') {
protectionRef.current = new ContentProtection({
modules: {
rightClick: { enabled: true },
keyboardShortcuts: { enabled: true },
textSelection: { enabled: true }
}
});
}
return () => {
if (protectionRef.current) {
protectionRef.current.destroy();
}
};
}, []);
return (
<div>
<h1>Protected Content</h1>
<p>Try right-clicking or selecting text</p>
</div>
);
}Svelte
Installation
npm install disable-right-clickUsage in Svelte Component
<script>
import { onMount, onDestroy } from 'svelte';
import ContentProtection from 'disable-right-click';
let protection = null;
let isProtected = false;
onMount(() => {
protection = new ContentProtection({
modules: {
rightClick: { enabled: true },
keyboardShortcuts: { enabled: true },
textSelection: { enabled: true }
}
});
isProtected = true;
});
onDestroy(() => {
if (protection) {
protection.destroy();
}
});
function toggleProtection() {
if (protection) {
if (isProtected) {
protection.disableAll();
isProtected = false;
} else {
protection.enableAll();
isProtected = true;
}
}
}
</script>
<div>
<h1>Protected Content</h1>
<button on:click={toggleProtection}>
{isProtected ? 'Disable' : 'Enable'} Protection
</button>
<p>Try right-clicking or selecting text</p>
</div>Nuxt.js
Installation
npm install disable-right-clickUsage in Nuxt Plugin
// plugins/contentProtection.client.js
import ContentProtection from 'disable-right-click';
export default defineNuxtPlugin((nuxtApp) => {
const protection = new ContentProtection({
modules: {
rightClick: { enabled: true },
keyboardShortcuts: { enabled: true },
textSelection: { enabled: true }
}
});
return {
provide: {
contentProtection: protection
}
};
});
// In component
export default {
setup() {
const { $contentProtection } = useNuxtApp();
// Use $contentProtection
}
}TypeScript
The library is written in TypeScript and includes full type definitions:
import ContentProtection, {
GlobalOptions,
RightClickOptions,
KeyboardShortcutsOptions
} from 'disable-right-click';
const options: GlobalOptions = {
modules: {
rightClick: {
enabled: true,
selector: '.protected'
} as RightClickOptions,
keyboardShortcuts: {
enabled: true,
shortcuts: ['Ctrl+C', 'Ctrl+V']
} as KeyboardShortcutsOptions
}
};
const protection = new ContentProtection(options);📚 Module Documentation
1. Right-Click Protection
Disable context menu globally or on specific elements.
const protection = new ContentProtection({
modules: {
rightClick: {
enabled: true,
selector: 'img', // Optional: only block on images
customMenu: false, // Show custom menu instead
customMenuItems: [
{ label: 'Custom Action', action: () => console.log('Clicked') }
],
onBlock: (event) => console.log('Right-click blocked', event)
}
}
});Options:
enabled- Enable/disable the moduleselector- CSS selector to limit blocking (optional)customMenu- Show custom context menu instead of blockingcustomMenuItems- Array of custom menu itemsonBlock- Callback when right-click is blocked
2. Keyboard Shortcuts Protection
Block keyboard shortcuts like Ctrl+C, Ctrl+V, F12, etc.
const protection = new ContentProtection({
modules: {
keyboardShortcuts: {
enabled: true,
shortcuts: ['Ctrl+C', 'Ctrl+V', 'F12', 'Ctrl+U'],
whitelist: false, // Block list mode (default)
allowList: ['Ctrl+F'], // Always allow these shortcuts
onBlock: (event) => console.log('Shortcut blocked', event)
}
}
});Default Blocked Shortcuts:
- Copy/Paste:
Ctrl+C,Ctrl+V,Ctrl+X,Ctrl+A - Save/Print:
Ctrl+S,Ctrl+P,Ctrl+Shift+S - View Source:
Ctrl+U,Ctrl+Shift+U - Developer Tools:
F12,Ctrl+Shift+I,Ctrl+Shift+J,Ctrl+Shift+C - Navigation:
Ctrl+N,Ctrl+T,Ctrl+W - Find:
Ctrl+F,Ctrl+H - Bookmark:
Ctrl+D - Refresh:
F5,Ctrl+R,Ctrl+Shift+R - Zoom:
Ctrl+Plus,Ctrl+Minus,Ctrl+0 - Fullscreen:
F11
Options:
enabled- Enable/disable the moduleshortcuts- Array of shortcuts to block (defaults to common shortcuts)whitelist- If true, only allow shortcuts inallowListallowList- Shortcuts to always allowselector- CSS selector to limit blocking (optional)
3. Text Selection Protection
Prevent users from selecting text.
const protection = new ContentProtection({
modules: {
textSelection: {
enabled: true,
selector: '.protected', // Optional: only protect specific elements
useCSS: true, // Use CSS user-select: none
onBlock: (event) => console.log('Selection blocked', event)
}
}
});Options:
enabled- Enable/disable the moduleselector- CSS selector to limit protection (optional)useCSS- Apply CSSuser-select: none(default: true)
4. Drag & Drop Protection
Prevent dragging images and content.
const protection = new ContentProtection({
modules: {
dragDrop: {
enabled: true,
selector: 'img', // Optional: only protect images
onBlock: (event) => console.log('Drag blocked', event)
}
}
});Options:
enabled- Enable/disable the moduleselector- CSS selector to limit protection (optional)
5. Developer Tools Protection
Detect and handle when DevTools are opened.
const protection = new ContentProtection({
modules: {
developerTools: {
enabled: true,
warn: true, // Show alert when DevTools detected
redirect: 'about:blank', // Redirect to URL (optional)
autoClose: false, // Try to close DevTools (limited effectiveness)
onBlock: (event) => console.log('DevTools detected', event)
}
}
});Options:
enabled- Enable/disable the modulewarn- Show alert when DevTools detectedredirect- URL to redirect to when DevTools detectedautoClose- Attempt to close DevTools (limited effectiveness)
Note: DevTools detection has limited effectiveness. Determined users can still access DevTools.
6. Print Protection
Block print operations.
const protection = new ContentProtection({
modules: {
print: {
enabled: true,
onBlock: (event) => console.log('Print blocked', event)
}
}
});Options:
enabled- Enable/disable the module
7. Clipboard Protection
Monitor and block clipboard operations.
const protection = new ContentProtection({
modules: {
clipboard: {
enabled: true,
clearOnCopy: true, // Clear clipboard when copy is attempted
onBlock: (event) => console.log('Clipboard blocked', event)
}
}
});Options:
enabled- Enable/disable the moduleclearOnCopy- Clear clipboard data when copy is attemptedselector- CSS selector to limit protection (optional)
8. Image Protection
Protect images with overlays and watermarks.
const protection = new ContentProtection({
modules: {
image: {
enabled: true,
selector: 'img', // Optional: only protect specific images
watermark: true, // Add watermark overlay
watermarkText: 'Protected Content', // Or function: () => `User: ${userEmail}`
onBlock: (event) => console.log('Image protected', event)
}
}
});Options:
enabled- Enable/disable the moduleselector- CSS selector for images to protect (default: 'img')watermark- Add watermark overlay to imageswatermarkText- Watermark text or function returning text
9. Screenshot Protection
Detect screenshot attempts (limited effectiveness).
const protection = new ContentProtection({
modules: {
screenshot: {
enabled: true,
showWarning: true, // Show warning overlay
watermark: true, // Add watermark to content
onBlock: (event) => console.log('Screenshot detected', event)
}
}
});Options:
enabled- Enable/disable the moduleshowWarning- Show warning overlay when detectedwatermark- Add watermark to content
⚠️ Warning: Screenshot detection has very limited effectiveness in browsers. This is a best-effort deterrent.
10. Frame Busting Protection
Prevent the page from being embedded in iframes.
const protection = new ContentProtection({
modules: {
frameBusting: {
enabled: true,
redirect: 'https://example.com', // Redirect if embedded (optional)
allowSameOrigin: true, // Allow same-origin iframes
onBlock: (event) => console.log('Iframe detected', event)
}
}
});Options:
enabled- Enable/disable the moduleredirect- URL to redirect to if embeddedallowSameOrigin- Allow same-origin iframes
11. View Source Protection
Block view source operations.
const protection = new ContentProtection({
modules: {
viewSource: {
enabled: true,
onBlock: (event) => console.log('View source blocked', event)
}
}
});Options:
enabled- Enable/disable the module
12. Download Protection
Block download operations.
const protection = new ContentProtection({
modules: {
download: {
enabled: true,
selector: 'img', // Optional: only protect specific elements
onBlock: (event) => console.log('Download blocked', event)
}
}
});Options:
enabled- Enable/disable the moduleselector- CSS selector to limit protection (optional)
🔄 Dynamic Control
Enable/disable modules at runtime:
// Enable a module
protection.enableModule('keyboardShortcuts');
// Disable a module
protection.disableModule('rightClick');
// Check if module is enabled
const isEnabled = protection.isModuleEnabled('textSelection');
// Update module options
protection.updateModule('rightClick', {
selector: '.new-selector'
});
// Enable all modules
protection.enableAll();
// Disable all modules
protection.disableAll();
// Destroy all modules
protection.destroy();🔔 Event System
Listen to protection events:
const protection = new ContentProtection({
// Global event handler
onEvent: (event, data) => {
console.log('Event:', event, data);
},
modules: {
rightClick: { enabled: true }
}
});
// Listen to specific events
protection.on('blocked', (data) => {
console.log('Right-click blocked', data);
});
protection.on('shortcutBlocked', (data) => {
console.log('Shortcut blocked', data);
});
protection.on('selectionBlocked', (data) => {
console.log('Selection blocked', data);
});Available Events:
blocked- Right-click blockedshortcutBlocked- Keyboard shortcut blockedselectionBlocked- Text selection blockeddragBlocked- Drag operation blockeddropBlocked- Drop operation blockeddevtoolsDetected- Developer tools detectedprintBlocked- Print operation blockedcopyBlocked- Copy operation blockedpasteBlocked- Paste operation blockedscreenshotDetected- Screenshot detectediframeDetected- Iframe detectedviewSourceBlocked- View source blockeddownloadBlocked- Download blocked
🧱 Full API
ContentProtection Class
class ContentProtection {
constructor(options?: GlobalOptions);
enableModule(name: ModuleName): void;
disableModule(name: ModuleName): void;
getModule(name: ModuleName): BaseModule | undefined;
isModuleEnabled(name: ModuleName): boolean;
updateModule(name: ModuleName, options: Partial<ModuleOptions>): void;
enableAll(): void;
disableAll(): void;
destroy(): void;
on(event: string, callback: (data?: any) => void): void;
off(event: string, callback: (data?: any) => void): void;
}🏗️ Project Structure
disable-right-click/
├── src/
│ ├── core/
│ │ ├── ContentProtection.ts
│ │ ├── BaseModule.ts
│ │ └── EventEmitter.ts
│ ├── modules/
│ │ ├── RightClickProtection.ts
│ │ ├── KeyboardShortcutsProtection.ts
│ │ ├── TextSelectionProtection.ts
│ │ └── ... (other modules)
│ ├── types/
│ │ └── index.ts
│ └── index.ts
├── dist/
│ ├── index.js (CommonJS)
│ ├── index.mjs (ES Module)
│ ├── index.d.ts (TypeScript definitions)
│ └── index.d.mts (TypeScript definitions for ESM)
├── package.json
├── tsconfig.json
└── README.md🧪 Development
Build
npm run buildDevelopment
The library is built with TypeScript and uses tsup for bundling. Source code is in the src/ directory.
🪪 License
MIT License - see LICENSE file for details.
🙌 Contributing
We welcome contributions! Please read our Contributing Guide for details on:
- Code of conduct
- Development setup
- Code style guidelines
- Pull request process
- Issue reporting
Quick Start for Contributors
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Make your changes
- Test thoroughly
- Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
For more details, see CONTRIBUTING.md.
⭐ Support
If you find this package useful, please:
- ⭐ Star it on GitHub
- 📦 Use it in your projects
- 🐛 Report bugs via Issues
- 💡 Suggest features via Issues
- 🤝 Contribute via Pull Requests
⚠️ Limitations & Warnings
Not a Security Solution: This library is a deterrent, not a security measure. Determined users can still access content.
Browser Limitations: Some features have limited effectiveness:
- Screenshot detection is unreliable
- Developer tools detection can be bypassed
- Clipboard blocking can be circumvented
User Experience: Aggressive protection may frustrate legitimate users. Use judiciously.
Accessibility: Some protections may interfere with assistive technologies. Test thoroughly.
Performance: Enabling many modules may impact page performance. Monitor and optimize as needed.
🔄 Migration Guide
If you're migrating from a previous version or similar library:
From Basic Right-Click Disable
// Old approach (manual event handling)
document.addEventListener('contextmenu', (e) => e.preventDefault());
// New approach (modular system)
import ContentProtection from 'disable-right-click';
const protection = new ContentProtection({
modules: {
rightClick: { enabled: true }
}
});From Other Protection Libraries
The modular architecture allows you to enable only what you need:
import ContentProtection from 'disable-right-click';
// Enable specific protections
const protection = new ContentProtection({
modules: {
rightClick: { enabled: true },
keyboardShortcuts: { enabled: true },
textSelection: { enabled: true }
// Only enable what you need
}
});