編輯長文時,瀏覽器崩潰、斷電、誤關標籤頁可能導致內容丟失。自動保存草稿功能(如 WordPress、CSDN、掘金)能定時將編輯器內容異步提交至服務器,並在異常時恢復。本文提供完整的前後端實現方案。
// api/draft.php
require_once 'db.php'; // PDO 連接
session_start();
header('Content-Type: application/json');
$action = $_POST['act'] ?? '';
$userId = $_SESSION['user_id'] ?? 0;
if (!$userId) exit(json_encode(['code'=>-1, 'msg'=>'未登錄']));
switch ($action) {
case 'autosave':
$title = trim($_POST['title'] ?? '');
$content = $_POST['content'] ?? '';
$postTime = (int)($_POST['postTime'] ?? time());
if (!$title && !$content) exit(json_encode(['code'=>0, 'msg'=>'內容為空,無需保存']));
$stmt = $pdo->prepare("
INSERT INTO drafts (user_id, title, content, post_time, updated_at)
VALUES (?, ?, ?, ?, NOW())
ON DUPLICATE KEY UPDATE
title=VALUES(title), content=VALUES(content), post_time=VALUES(post_time), updated_at=NOW()
");
// 假設 drafts 表有唯一索引 (user_id, post_time) 或單用戶單草稿
$stmt->execute([$userId, $title, $content, $postTime]);
exit(json_encode(['code'=>1, 'msg'=>'保存成功', 'id'=>$pdo->lastInsertId()]));
case 'loaddraft':
$stmt = $pdo->prepare("SELECT * FROM drafts WHERE user_id = ? ORDER BY updated_at DESC LIMIT 1");
$stmt->execute([$userId]);
$draft = $stmt->fetch();
exit(json_encode(['code'=>1, 'data'=>$draft ?: null]));
case 'cleardraft':
$pdo->prepare("DELETE FROM drafts WHERE user_id = ?")->execute([$userId]);
exit(json_encode(['code'=>1, 'msg'=>'草稿已清除']));
default:
exit(json_encode(['code'=>-1, 'msg'=>'非法操作']));
}
CREATE TABLE `drafts` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`user_id` INT UNSIGNED NOT NULL,
`title` VARCHAR(255) DEFAULT '',
`content` LONGTEXT,
`post_time` INT UNSIGNED NOT NULL,
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `uk_user_post` (`user_id`, `post_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
<script>
// 配置
const AUTOSAVE_INTERVAL = 30000; // 30秒
const EDITOR_ID = 'content'; // 編輯器 textarea/id 或 iframe
const TITLE_ID = 'title';
// 狀態
let autosaveTimer = null;
let lastContent = '';
let lastTitle = '';
// 工具:獲取編輯器內容(支援 textarea / iframe / 常見富文本編輯器)
function getEditorContent() {
const el = document.getElementById(EDITOR_ID);
if (!el) return '';
if (el.tagName === 'TEXTAREA' || el.tagName === 'INPUT') return el.value;
if (el.tagName === 'IFRAME') {
try { return el.contentDocument.body.innerHTML; } catch(e) { return ''; }
}
// contentEditable div
return el.innerHTML;
}
// 核心:發送自動保存
function doAutosave() {
const title = document.getElementById(TITLE_ID)?.value || '';
const content = getEditorContent();
const postTime = Date.now();
if (title === lastTitle && content === lastContent) {
updateStatus('內容無變化,跳過保存');
return;
}
updateStatus('正在保存草稿...');
fetch('api/draft.php', {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: new URLSearchParams({act:'autosave', title, content, postTime})
})
.then(r => r.json())
.then(res => {
if (res.code === 1) {
lastTitle = title;
lastContent = content;
updateStatus('草稿已自動保存 (' + new Date().toLocaleTimeString() + ')');
loadDraftList(); // 可選:更新側邊欄草稿列表
} else {
updateStatus('保存失敗:' + res.msg);
}
})
.catch(err => updateStatus('網絡錯誤:' + err));
}
// 定時器控制
function startAutosave() {
if (autosaveTimer) return;
autosaveTimer = setInterval(doAutosave, AUTOSAVE_INTERVAL);
doAutosave(); // 立即執行一次
updateStatus('自動保存已啟動,每 ' + (AUTOSAVE_INTERVAL/1000) + ' 秒保存一次');
}
function stopAutosave() {
clearInterval(autosaveTimer);
autosaveTimer = null;
updateStatus('自動保存已停止');
}
// 載入草稿(頁面初始化時調用)
function loadDraftOnInit() {
fetch('api/draft.php', {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: 'act=loaddraft'
})
.then(r => r.json())
.then(res => {
if (res.code === 1 && res.data) {
if (confirm('發現未提交的草稿(' + new Date(res.data.updated_at*1000).toLocaleString() + '),是否恢復?')) {
document.getElementById(TITLE_ID).value = res.data.title;
setEditorContent(res.data.content);
lastTitle = res.data.title;
lastContent = res.data.content;
updateStatus('草稿已恢復');
}
}
});
}
// 發布成功後調用
function onPublishSuccess() {
fetch('api/draft.php', {method:'POST', body:'act=cleardraft'});
stopAutosave();
lastTitle = lastContent = '';
}
// 輔助
function updateStatus(msg) {
const el = document.getElementById('autosaveStatus');
if (el) el.textContent = msg;
console.log('[Autosave]', msg);
}
function setEditorContent(html) {
const el = document.getElementById(EDITOR_ID);
if (!el) return;
if (el.tagName === 'TEXTAREA' || el.tagName === 'INPUT') el.value = html;
else if (el.tagName === 'IFRAME') {
try { el.contentDocument.body.innerHTML = html; } catch(e) {}
} else { el.innerHTML = html; }
}
// 頁面加載啟動
document.addEventListener('DOMContentLoaded', () => {
loadDraftOnInit();
startAutosave();
// 綁定發布按鈕
document.getElementById('btnPublish')?.addEventListener('click', onPublishSuccess);
});
</script>
<!-- 狀態顯示區域 -->
<div id="autosaveStatus" style="padding:5px;background:#f0f0f0;margin:5px 0;font-size:12px;color:#666">初始化中...</div>
LZString 壓縮,後端解壓。article_id 或 token 區分。change 事件,可直接觸發保存。自動保存草稿是提升內容創作體驗的關鍵功能,上述方案輕量、易集成,可根據業務複雜度逐步增強。