萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 禁止右鍵選單與文字選擇:跨瀏覽器兼容方案與現代替代思考

前言

雖然「禁止右鍵/複製」無法真正保護前端代碼與內容(使用者可通過開發者工具、停用 JS、列印列印等繞過),但在特定業務場景(考試系統、付費內容預覽、版權敏感圖片)仍有需求。本文提供兩套經典兼容代碼,並分析其局限性與現代替代策略。

方案一:事件攔截經典寫法(支援 IE6+、Firefox、Chrome、Safari)

<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>

方案二:現代簡潔寫法(IE5+、標準瀏覽器)

<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>

三、核心 API 對照表

功能IE/Edge/ChromeFirefox標準 DOM
右鍵選單oncontextmenuoncontextmenucontextmenu 事件
滑鼠按下onmousedownonmousedownmousedown 事件
文字選擇onselectstart無user-select: none (CSS)

四、現代最佳實踐:CSS + 選擇性 JS

1. 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"> 或特定容器。

2. CSS 隱藏右鍵選單(實驗性)

* { context-menu: none; } /* 極少數瀏覽器支援 */

3. JS 兜底(僅針對不支援 CSS 的舊瀏覽器)

// 僅在 CSS 不生效時啟用
if ('userSelect' in document.documentElement.style === false) {
    document.oncontextmenu = () => false;
    document.onselectstart = () => false;
}

五、為什麼這不算「安全」?

  • 開發者工具:F12 → Elements/Console/Network 可獲取所有資源
  • 停用 JavaScript:瀏覽器設定一鍵關閉 JS,所有攔截失效
  • 列印/存檔:Ctrl+P 列印為 PDF、Ctrl+S 儲存網頁完整資源
  • 擴充套件:啟用右鍵、複製、截圖等外掛
  • 行動裝置:長按選單、分享表單完全不受桌面端 JS 控制

六、真正的內容保護策略

  1. 伺服端渲染 + 權限控制:未授權用戶根本拿不到 HTML 內容
  2. 數位浮水印:圖片/文檔隱形水印追溯洩露源
  3. DRM / 加密播放:視頻內容加密、授權播放
  4. 法律手段:版權聲明、用戶協議、DMCA 下架

結語

前端「禁止右鍵/複製」只能阻擋 90% 的非技術用戶,**絕不能作為安全防線**。建議採用 CSS user-select: none 為主、JS 兜底為輔** 的漸進增強策略,並在業務層面通過權限控制、水印、法律手段實現真正保護。代碼僅供學習事件模型與跨瀏覽器兼容技巧參考。

copyright © 萬盛學電腦網 all rights reserved