頁面包含 <textarea id="detail"> 與超連結 <a href="a.jsp">。點擊超連結前將文字區內容存入 Cookie(有效期 5 分鐘),5 分鐘內再次造訪頁面時自動填入原內容。
<textarea id="detail" name="detail" cols="50" rows="20"></textarea>
<a href="a.jsp" onclick="saveCookie()">前往 a.jsp</a>
<script>
function saveCookie() {
var v = document.getElementById('detail').value;
var d = new Date();
d.setMinutes(d.getMinutes() + 5); // 5 分鐘後過期
// encodeURIComponent 處理特殊字元,防止分號、逗號截斷
document.cookie = 'detail=' + encodeURIComponent(v) + ';expires=' + d.toGMTString() + ';path=/';
}
window.onload = function () {
// 使用正則從 cookie 字串中提取 detail 值
var m = /(^|;\s*)detail=([^;]+)/.exec(document.cookie);
if (m) {
// decodeURIComponent 還原原始內容
document.getElementById('detail').value = decodeURIComponent(m[2]);
}
};
</script>
encodeURIComponent / decodeURIComponent 確保內容含特殊字元(換行、分號、等號)不破壞 Cookie 格式。toGMTString() 產生符合 RFC 1123 的日期字串,瀏覽器通用。;path=/ 使整站可讀取,否則僅限當前目錄。/(^|;\s*)detail=([^;]+)/ 匹配開頭或分號後的 detail=,捕獲值直到下一個分號。onclick 先存 Cookie 再跳轉;window.onload 保證 DOM 就緒後讀取。Set-Cookie: detail=...; HttpOnly; Secure,但 JavaScript 將無法讀寫,需由後端協助。localStorage.setItem('detail', v) 更簡單、容量更大 (5MB)、不隨請求傳送。domain=.example.com 可跨子網域共享。<!DOCTYPE html>
<html><head><meta charset="UTF-8"><title>Cookie 文字區示範</title></head><body>
<textarea id="detail" cols="50" rows="10"></textarea><br>
<a href="a.jsp" onclick="saveCookie()">送出並跳轉</a>
<script>
// ... 上述 saveCookie / onload 程式碼 ...
</script>
</body></html>
此方案純前端實現,無需後端配合,適合簡單的暫存草稿、表單保護等場景。