-

Dưới đây là bài hướng dẫn chi tiết từng bước (Topic) giúp bạn tự xây dựng một Webform lưu trữ dữ liệu vào IndexedDB ngay trên Blogspot.

Hướng dẫn: Tự làm Webform lưu trữ IndexedDB trên nền tảng Blogspot

1. Ý tưởng cốt lõi là gì?

  • Blogspot: Đóng vai trò là giao diện (Frontend) hiển thị form.

  • HTML/CSS/JavaScript: Tạo form và xử lý sự kiện khi người dùng nhập/ấn nút.

  • IndexedDB: Là một database dạng NoSQL tích hợp sẵn trong trình duyệt (Chrome, Safari, Firefox...). Dữ liệu sẽ được lưu trực tiếp trên máy của người dùng, cho phép lưu trữ dung lượng lớn và hoạt động ngay cả khi mất mạng (Offline).

2. Các bước thực hiện chi tiết

Bước 1: Tạo Form nhập liệu bằng HTML

Bạn cần một giao diện form cơ bản để người dùng điền thông tin (ví dụ: Form quản lý thông tin học viên/khách hàng).

Bước 2: Viết JavaScript kết nối và xử lý IndexedDB

Đoạn code JavaScript này sẽ làm các nhiệm vụ:

  1. Khởi tạo (hoặc mở) Database có tên WebFormDB.

  2. Tạo một bảng (Object Store) tên là users.

  3. Lắng nghe sự kiện click nút "Lưu dữ liệu" để lấy thông tin từ Form lưu vào Database.

  4. Đọc và hiển thị lại dữ liệu đã lưu lên màn hình.

3. Trọn bộ Source Code mẫu (HTML + JS)

Bạn có thể copy đoạn code dưới đây để test trực tiếp. Đoạn code này đã bao gồm cả Form và phần xử lý IndexedDB:

HTML
<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Webform IndexedDB trên Blogspot</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; background-color: #f4f4f9; }
        .form-container { max-width: 400px; background: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }
        .form-group { margin-bottom: 15px; }
        .form-group label { display: block; margin-bottom: 5px; font-weight: bold; }
        .form-group input { width: 100%; padding: 8px; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; }
        button { background: #007bff; color: white; padding: 10px 15px; border: none; border-radius: 4px; cursor: pointer; }
        button:hover { background: #0056b3; }
        .data-list { margin-top: 20px; max-width: 400px; }
        .data-item { background: #e9ecef; padding: 10px; margin-bottom: 5px; border-radius: 4px; display: flex; justify-content: space-between; }
    </style>
</head>
<body>

<div class="form-container">
    <h3>Form Đăng Ký Thành Viên</h3>
    <form id="contactForm">
        <div class="form-group">
            <label for="username">Họ và tên:</label>
            <input type="text" id="username" required>
        </div>
        <div class="form-group">
            <label for="email">Email:</label>
            <input type="email" id="email" required>
        </div>
        <button type="submit">Lưu vào IndexedDB</button>
    </form>
</div>

<h3>Danh sách đã lưu dữ liệu (Offline):</h3>
<div id="dataList" class="data-list"></div>

<script>
    let db;
    // 1. Khởi tạo / Mở database
    const request = indexedDB.open("WebFormDB", 1);

    request.onupgradeneeded = function(event) {
        db = event.target.result;
        // Tạo bảng 'users' với khóa chính tự tăng 'id'
        if (!db.objectStoreNames.contains("users")) {
            db.createObjectStore("users", { keyPath: "id", autoIncrement: true });
        }
    };

    request.onsuccess = function(event) {
        db = event.target.result;
        printData(); // Hiển thị dữ liệu cũ nếu có
    };

    request.onerror = function(event) {
        console.error("Lỗi kết nối IndexedDB:", event.target.errorCode);
    };

    // 2. Xử lý khi nhấn Submit Form
    document.getElementById("contactForm").addEventListener("submit", function(e) {
        e.preventDefault();

        const username = document.getElementById("username").value;
        const email = document.getElementById("email").value;

        const transaction = db.transaction(["users"], "readwrite");
        const objectStore = transaction.objectStore("users");
        
        const newUser = { name: username, email: email, timestamp: new Date().toLocaleString() };
        const addRequest = objectStore.add(newUser);

        addRequest.onsuccess = function() {
            alert("Lưu dữ liệu thành công vào trình duyệt!");
            document.getElementById("contactForm").reset();
            printData(); // Cập nhật lại danh sách hiển thị
        };
    });

    // 3. Hàm đọc dữ liệu từ IndexedDB và in ra màn hình
    function printData() {
        const dataList = document.getElementById("dataList");
        dataList.innerHTML = ""; // Xóa dữ liệu cũ trên giao diện

        const objectStore = db.transaction("users").objectStore("users");
        
        // Dùng Cursor để duyệt qua từng dòng dữ liệu
        objectStore.openCursor().onsuccess = function(event) {
            const cursor = event.target.result;
            if (cursor) {
                const div = document.createElement("div");
                div.className = "data-item";
                div.innerHTML = `<span><strong>${cursor.value.name}</strong> (${cursor.value.email})</span>`;
                dataList.appendChild(div);
                cursor.continue();
            }
        };
    }
</script>

</body>
</html>

4. Cách tích hợp đoạn code này vào Blogspot

Để đưa form này lên trang Blogspot của bạn, hãy làm theo các bước sau:

  1. Đăng nhập vào trang quản trị Blogger.com.

  2. Vào mục Trang (Pages) hoặc Bài đăng (Posts) -> Chọn Tạo trang mới (hoặc Bài đăng mới).

  3. Ở góc trên cùng bên trái của trình soạn thảo, chuyển từ chế độ Chế độ xem soạn thảo (Compose view) sang Chế độ xem HTML (HTML view).

  4. Xóa hết các code mặc định đi và Dán toàn bộ đoạn code mẫu ở mục 3 vào.

  5. Nhấn Xuất bản (Publish).

💡 Mẹo kiểm tra dữ liệu: Trên trang Blogspot vừa tạo, bạn bấm F12 (nút Kiểm tra phần tử) -> Chọn tab Application (Ứng dụng) -> Nhìn sang cột bên trái tìm mục IndexedDB -> Bấm vào WebFormDB để xem dữ liệu thực tế đang được lưu trữ dưới trình duyệt của bạn.

5. Ưu điểm và Hạn chế của giải pháp này

Ưu điểm 🚀Hạn chế ⚠️
Miễn phí 100%: Không tốn tiền mua database hay hosting.Dữ liệu cục bộ: Dữ liệu lưu trên máy/trình duyệt của ai thì chỉ người đó thấy (không đồng bộ về máy của Admin).
Chạy Offline tốt: Mất mạng vẫn nhập form và lưu dữ liệu bình thường.Dễ mất dữ liệu: Nếu người dùng xóa cache trình duyệt (Clear Cookies and Site Data), dữ liệu sẽ bị xóa sạch.
Bảo mật quyền riêng tư: Phù hợp làm các app ghi chú cá nhân, nhật ký, hoặc bộ lọc sản phẩm ngay trên Blogspot.

🔥 Nâng cấp nâng cao (Gợi ý mở rộng):

Nếu bạn muốn làm một form thu thập thông tin khách hàng (Admin cần nhận được dữ liệu), bạn có thể dùng IndexedDB làm nơi lưu tạm khi mất mạng. Khi có mạng trở lại, bạn viết thêm một đoạn code JS để "đẩy" (Sync) dữ liệu từ IndexedDB này lên Google Sheets hoặc Firebase thông qua API.


Webform IndexedDB trên Blogspot

Form Đăng Ký Thành Viên

Danh sách đã lưu dữ liệu (Offline):