有些網站基於特定考量,會希望限制使用者按 F5 刷新、按右鍵開啟選單等行為。下面示範幾種常見的鍵盤與滑鼠事件攔截寫法(僅供學習參考,實際使用請審慎評估使用者體驗)。
<script language="javascript">
// 禁止用 F5 鍵
function document.onkeydown()
{
if ( event.keyCode==116)
{
event.keyCode = 0;
event.cancelBubble = true;
return false;
}
}
// 禁止右鍵彈出菜單
function document.oncontextmenu()
{
return false;
}
// 下面代碼實現全屏顯示
function window.onload(){
var Request = new Array();//保存參數
var s = location.search.substring(1);
if (s && s!=""){
var list = s.split("&");
for (var i=0; i < list.length; i++){
var pair = list[i].split("=");
if (pair[0] && pair[0] !=""){
Request[unescape(pair[0])] = unescape(pair[1]);
}
}
}
var fullscreen=Request["fullscreen"];
if(fullscreen!="yes"){
var file =self.location;
var a = window.open("about:blank","","fullscreen=yes")
self.opener=null
self.close()
a.location=file + "?fullscreen=yes";
}
}
</script>
下面這段則更進一步,同時攔截右鍵、F1、F5、F11、Ctrl+N、Shift+F10、退格鍵等多種操作:
<script language="Javascript"><!--
// 屏蔽鼠標右鍵、Ctrl+N、Shift+F10、F11、F5刷新、退格鍵
// Author: meizz(梅花雨) 2002-6-18
function document.oncontextmenu(){event.returnValue=false;}//屏蔽鼠標右鍵
function window.onhelp(){return false} //屏蔽 F1 幫助
function document.onkeydown()
{
if ((window.event.altKey)&&
((window.event.keyCode==37)|| //屏蔽 Alt+ 方向鍵 ←
(window.event.keyCode==39))) //屏蔽 Alt+ 方向鍵 →
{
alert("不准你使用ALT+方向鍵前進或後退網頁!");
event.returnValue=false;
}
if ((event.keyCode==8) || //屏蔽退格刪除鍵
(event.keyCode==116)|| //屏蔽 F5 刷新鍵
(event.ctrlKey && event.keyCode==82)){ //Ctrl + R
event.keyCode=0;
event.returnValue=false;
}
if (event.keyCode==122){event.keyCode=0;event.returnValue=false;} //屏蔽 F11
if (event.ctrlKey && event.keyCode==78) event.returnValue=false; //屏蔽 Ctrl+n
if (event.shiftKey && event.keyCode==121)event.returnValue=false; //屏蔽 shift+F10
if (window.event.srcElement.tagName == "A" && window.event.shiftKey)
window.event.returnValue = false; //屏蔽 shift 加鼠標左鍵新開一網頁
if ((window.event.altKey)&&(window.event.keyCode==115)) //屏蔽 Alt+F4
{
window.showModelessDialog("about:blank","","dialogWidth:1px;dialogheight:1px");
return false;
}
}
</script>
需要提醒的是,這類限制並非真正安全的防護手段,例如攔截 Alt+方向鍵時,若使用者按住 Alt 不放並用滑鼠關掉警告框,封鎖就會失效。因此這類技巧更適合用於特定情境的體驗控制,而非安全防護。