想保存網頁上的精美圖片或精彩文字,一般做法是選取目標後按右鍵,從彈出選單裡挑「圖片另存為」或「複製」。有些網站會把這些操作鎖起來,以下整理四段常用寫法。
<script type="text/javascript">
document.oncontextmenu = new Function("event.returnValue = false;");
document.onselectstart = new Function("event.returnValue = false;");
</script>
上面那種寫法在 Firefox 會失效,需要額外攔 mousedown:
<!DOCTYPE html>
<html>
<head>
<title>禁止滑鼠右鍵</title>
<meta charset="utf-8">
</head>
<body>
<div class="poo">這個頁面不能使用滑鼠右鍵</div>
<!-- 禁止滑鼠右鍵 -->
<script type="text/javascript">
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; // for IE5+
document.onmousedown = norightclick; // for others
</script>
</body>
</html>
<script type="text/javascript">
var omitformtags = ["input", "textarea", "select"];
omitformtagsomitformtags = omitformtags.join("|");
function disableselect(e){
if (omitformtags.indexOf(e.target.tagName.toLowerCase()) == -1) {
return false;
}
}
function reEnable(){
return true;
}
if (typeof document.onselectstart != "undefined") {
document.onselectstart = new Function("return false");
} else {
document.onmousedown = disableselect;
document.onmouseup = reEnable;
}
</script>
這裡刻意排除 input、textarea、select,讓表單欄位仍能正常選取與複製,避免把網站自己的功能也一起鎖死。
document.onkeydown = function(){
if (event.ctrlKey) return false;
}
實務上要提醒的是:這類限制只能稍微提高保存門檻,並不具真正的保護力——使用者仍可關閉 JS、用開發者工具或直接從快取取得資源,同時也會傷害正常的可存取性操作。因此建議只用於確有必要,且務必提供替代的合法取得管道。