用戶填寫長表單時誤觸刷新導致數據丟失是常見痛點。本文對比 **IE 專有 CSS behavior 方案** 與 **通用 AJAX 自動保存草稿方案**,幫助你選擇適合項目的技術路線。
利用 IE 5+ 獨有的 behavior: url(#default#savehistory) 配合 <meta name="save" content="history"> 實現表單值在頁面刷新後自動恢復。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="save" content="history">
<title>表單數據自動保存演示</title>
<style type="text/css">
input { behavior: url(#default#savehistory); }
</style>
</head>
<body>
<div style="float: left;">
<ul>
<li><label style="width: 100px;">用戶名</label><input type="text" id="username" /></li>
<li><label style="width: 100px;">郵箱</label><input type="text" id="email" /></li>
</ul>
</div>
</body>
</html>
| 優點 | 缺點 |
|---|---|
| 零 JS 代碼,純 CSS/HTML 實現 | 僅 IE 支持,Chrome/Firefox/Safari/Edge 全部無效 |
| 無需後端配合,客戶端獨立完成 | 依賴用戶瀏覽器歷史記錄,清理歷史即失效 |
| 對輕量級內部系統(純 IE 環境)極其簡單 | 無法跨設備/瀏覽器同步,安全性不可控 |
結論:僅適用於極老舊的 IE-only 內網系統,現代 Web 開發**強烈不推薦**。
通用方案:前端定時將表單數據發送到後端 API,用戶返回時可一鍵恢復。
// 要保存的內容對象
const formContent = document.getElementById('content');
// 狀態提示容器
const autoSaveMsg = document.getElementById('AutoSaveMsg');
// 自動保存間隔 (60 秒)
const AUTO_SAVE_INTERVAL = 60000;
let autoSaveTimer;
// 初始化
setAutoSave();
// 定時保存函數
function autoSave() {
if (!formContent.value.trim()) return; // 內容為空不保存
const xhr = new XMLHttpRequest();
xhr.open('POST', 'inc/autosave.php', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
if (xhr.status === 200) {
autoSaveMsg.textContent = xhr.responseText; // 如 "草稿已於 10:30 自動保存"
}
};
xhr.send('postcontent=' + encodeURIComponent(formContent.value));
}
// 設置定時器
function setAutoSave() {
autoSaveTimer = setInterval(autoSave, AUTO_SAVE_INTERVAL);
}
// 手動恢復最後草稿
function autoSaveRestore() {
autoSaveMsg.textContent = '正在恢復草稿...';
const xhr = new XMLHttpRequest();
xhr.open('POST', 'inc/autosave.php', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
if (xhr.status === 200 && xhr.responseText.trim()) {
formContent.value = xhr.responseText;
autoSaveMsg.textContent = '草稿恢復成功!';
} else {
autoSaveMsg.textContent = '無可用草稿';
}
};
xhr.send('action=restore');
}
// 頁面卸載前最後嘗試保存(可選)
window.addEventListener('beforeunload', autoSave);
<?php
session_start();
header('Content-Type: text/plain; charset=utf-8');
$action = $_POST['action'] ?? 'save';
$userId = $_SESSION['user_id'] ?? 0; // 實際項目用真實用戶 ID
$draftKey = "draft_{$userId}_content";
if ($action === 'restore') {
echo $_SESSION[$draftKey] ?? '';
exit;
}
$content = $_POST['postcontent'] ?? '';
if ($content) {
$_SESSION[$draftKey] = $content;
// 生產環境建議存入資料庫,附帶時間戳、版本號
echo '草稿已於 ' . date('H:i:s') . ' 自動保存';
} else {
echo '內容為空,未保存';
}
<textarea id="content" rows="10" cols="60"></textarea>
<div id="AutoSaveMsg" style="margin-top: 8px; color: #666;"></div>
<button type="button" onclick="autoSaveRestore()">恢復最後保存的草稿</button>
<script src="autosave.js"></script>
beforeunload 事件| 維度 | CSS behavior | AJAX 自動保存 |
|---|---|---|
| 瀏覽器支持 | 僅 IE 5+ | 全瀏覽器 |
| 數據持久化 | 瀏覽器歷史 (易失) | 服務器/本地存儲 (可控) |
| 跨設備 | 不支持 | 支持 (需後端) |
| 安全性 | 低 | 可控 (加密、權限) |
| 實現複雜度 | 極低 | 中等 (需前後端配合) |
| 推薦場景 | 極老舊 IE 內網 | 所有現代 Web 項目 |