雖然「禁止右鍵/複製」無法真正保護前端代碼與內容(使用者可通過開發者工具、停用 JS、列印列印等繞過),但在特定業務場景(考試系統、付費內容預覽、版權敏感圖片)仍有需求。本文提供兩套經典兼容代碼,並分析其局限性與現代替代策略。
<script>
var message = "右鍵功能已禁用"; // 可自定義提示或留空
// IE 事件模型
function clickIE() {
if (document.all) {
alert(message);
return false;
}
}
// Netscape/標準事件模型
function clickNS(e) {
if (document.layers || (document.getElementById && !document.all)) {
if (e.which === 2 || e.which === 3) { // 中鍵/右鍵
alert(message);
return false;
}
}
}
// 綁定事件
if (document.layers) {
document.captureEvents(Event.MOUSEDOWN);
document.onmousedown = clickNS;
} else {
document.onmouseup = clickNS;
document.oncontextmenu = clickIE;
}
// 統一攔截 contextmenu
document.oncontextmenu = new Function("return false");
</script>
<script>
// 右鍵攔截
if (window.Event) document.captureEvents(Event.MOUSEUP);
function nocontextmenu() {
event.cancelBubble = true;
event.returnValue = false;
return false;
}
function norightclick(e) {
if (window.Event) {
if (e.which === 2 || e.which === 3) return false;
} else {
if (event.button === 2 || event.button === 3) {
event.cancelBubble = true;
event.returnValue = false;
return false;
}
}
}
document.oncontextmenu = nocontextmenu; // IE5+
document.onmousedown = norightclick; // 其他
// === 禁止文字選擇 ===
var omitFormTags = ["input", "textarea", "select"];
omitFormTags = omitFormTags.join("|");
function disableselect(e) {
// 表單元素允許選擇
if (omitFormTags.indexOf(e.target.tagName.toLowerCase()) === -1) {
return false;
}
}
function reEnable() { return true; }
if (typeof document.onselectstart !== "undefined") {
// IE/Chrome/Edge
document.onselectstart = new Function("return false");
} else {
// Firefox
document.onmousedown = disableselect;
document.onmouseup = reEnable;
}
</script>
| 功能 | IE/Edge/Chrome | Firefox | 標準 DOM |
|---|---|---|---|
| 右鍵選單 | oncontextmenu | oncontextmenu | contextmenu 事件 |
| 滑鼠按下 | onmousedown | onmousedown | mousedown 事件 |
| 文字選擇 | onselectstart | 無 | user-select: none (CSS) |
.no-select {
-webkit-user-select: none; /* Chrome/Safari */
-moz-user-select: none; /* Firefox */
-ms-user-select: none; /* IE10+ */
user-select: none; /* 標準 */
}
/* 允許輸入框選擇 */
.no-select input, .no-select textarea, .no-select select {
-webkit-user-select: text;
user-select: text;
}
套用:<body class="no-select"> 或特定容器。
* { context-menu: none; } /* 極少數瀏覽器支援 */
// 僅在 CSS 不生效時啟用
if ('userSelect' in document.documentElement.style === false) {
document.oncontextmenu = () => false;
document.onselectstart = () => false;
}
Ctrl+P 列印為 PDF、Ctrl+S 儲存網頁完整資源前端「禁止右鍵/複製」只能阻擋 90% 的非技術用戶,**絕不能作為安全防線**。建議採用 CSS user-select: none 為主、JS 兜底為輔** 的漸進增強策略,並在業務層面通過權限控制、水印、法律手段實現真正保護。代碼僅供學習事件模型與跨瀏覽器兼容技巧參考。