萬盛學電腦網

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

JavaScript 禁止網頁右鍵、複製、拖曳、另存新檔等操作的綜合方案

一、禁用右鍵選單

<script>
document.oncontextmenu = function() { return false; };
</script>

或綁定 mousedown 攔截右鍵:

document.onmousedown = function(e) {
    e = e || window.event;
    if (e.button === 2) { alert("禁止右鍵"); return false; }
};

二、禁止選取與複製

HTML 屬性法(舊式)

<body oncontextmenu="return false" onselectstart="return false" 
      ondragstart="return false" onbeforecopy="return false"
      oncopy="document.selection.empty()" onselect="document.selection.empty()">

JavaScript 事件法(較完整)

<script>
function disableselect(e) { return false; }
function reEnable() { return true; }

// IE
document.onselectstart = new Function("return false");

// Firefox/舊版
if (window.sidebar) {
    document.onmousedown = disableselect;
    document.onclick = reEnable;
}
</script>

三、CSS 僅樣式防複製(現代推薦)

<style>
body {
    -moz-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
    user-select: none;
}
</style>

此法不干擾 JS 事件,純樣式層面禁止使用者選取文字,相容性佳。

四、防止儲存網頁/檢視原始碼

<noscript><iframe src=""></iframe></noscript>

利用 <noscript> 在禁用 JS 環境下載入空 iframe 干擾另存新檔(效果有限,屬防君子不防小人)。

五、綜合鍵盤攔截範例

<script>
document.onkeydown = function(e) {
    e = e || window.event;
    // 禁用 F5 / Ctrl+F5 重新整理
    if (e.keyCode === 116 || (e.ctrlKey && e.keyCode === 116)) {
        e.keyCode = 0; e.returnValue = false; return false;
    }
    // 禁用 Ctrl+C 複製
    if (e.ctrlKey && e.keyCode === 67) { return false; }
    // 禁用 Alt+F4 關閉視窗(僅 IE 旧版有效)
    if (e.altKey && e.keyCode === 115) { window.close(); }
};
</script>

六、複製時自動附加版權資訊

function SetCopyContent() {
    event.returnValue = false;
    var content = document.title + "\r\n";
    content += document.getElementById("txt1").value + "\r\n";
    content += "本資源來自 " + location.href;
    window.clipboardData.setData('Text', content);
    alert("複製成功,請推薦給好友!");
}
<body oncopy="SetCopyContent()">

安全性提醒

  • 所有前端限制皆可繞過(關閉 JS、開發者工具、列印存 PDF 等),不可作為資料保護唯一手段。
  • 敏感資料應在後端管控輸出權限、加浮水印、或採用 DRM 方案。
  • 過度干擾使用者操作(如禁用右鍵)會嚴重損害使用者體驗,請審慎評估必要性。
copyright © 萬盛學電腦網 all rights reserved