出於保護內容或引導使用者操作的考量,網站有時會希望限制右鍵、選取、複製等行為。本文整理了以 JavaScript 實作各類頁面操作限制的寫法,涵蓋右鍵、複製、鍵盤按鍵與重新整理等常見情境,供開發者參考。
最基礎的做法是攔截 mousedown 事件,偵測是否為右鍵並阻擋:
<script type="text/javascript">
function block(oEvent){
if(window.event) oEvent=window.event;
if(oEvent.button==2) alert("滑鼠右鍵不可用");
}
document.onmousedown=block;
</script>
若希望靜默封鎖而不彈出提示,可直接將 contextmenu 事件的回傳值設為 false:
document.oncontextmenu = function(){ return false; }
透過 body 標籤上的一系列事件屬性,可同時封鎖選取、拖曳與複製:
<BODY oncontextmenu="return false" onselectstart="return false" ondragstart="return false" onbeforecopy="return false" oncopy="document.selection.empty()" onselect="document.selection.empty()">
兼顧 IE 與舊版 Netscape 的做法如下:
<SCRIPT language=JavaScript1.2>
function disableselect(e){ return false }
function reEnable(){ return true }
if (document.all){ document.onselectstart = new Function("return false") }
if (window.sidebar){ document.onmousedown=disableselect; document.onclick=reEnable }
</SCRIPT>
例如封鎖介於 A 到 D 之間的按鍵:
function ForbidKeys() {
var content = window.event.keyCode;
if (content >= 65 && content <= 68) {
window.event.returnValue = false;
}
}
攔截 keyCode 為 116 的按鍵即可阻擋重新整理:
function ForbidFreshPage() {
if ((window.event.ctrlKey && window.event.keyCode == 116) || window.event.keyCode == 116) {
window.event.keyCode = 0;
window.event.returnValue = false;
}
}
document.onkeydown = ForbidFreshPage;
除了 JavaScript,也能借助 CSS 達成禁用選取的效果:
<style>
body{
-moz-user-select:none;
behavior:expression(this.onselectstart=function(){return(false)});
}
</style>
需要特別注意的是,這類限制並非萬無一失。使用者仍可關閉 JavaScript、透過原始碼或開發者工具取得內容,因此這些技巧只能提高一般使用者的操作門檻,適合用於引導行為或輕度防護,不宜當成真正的資安手段。真正重要的資料,仍應在伺服器端做好存取控制。