以下是一段利用 JavaScript 為頁面添加密碼保護的範例。它透過 prompt 彈出輸入框,讓使用者輸入密碼,最多允許三次嘗試,密碼正確才繼續,否則返回上一頁:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>密碼保護相應頁面</title>
</head>
<body>
<SCRIPT LANGUAGE="JavaScript">
function password() {
var testV = 1;
var pass1 = prompt('請輸入密碼(密碼是shenlong):','');
while (testV < 3) {
if (!pass1) history.go(-1);
if (pass1 == "shenlong") { alert('密碼正確!'); break; }
testV+=1;
var pass1 = prompt('密碼錯誤!請重新輸入:');
}
if (pass1!="password" & testV ==3) history.go(-1);
return " ";
}
document.write(password());
</SCRIPT>
</body>
</html>
需要提醒的是,這種前端密碼保護僅能防止一般使用者隨意進入,密碼直接寫在客戶端源碼中,並不安全,切勿用於保護真正敏感的內容。若需要真正的存取控制,應在伺服器端進行驗證。