Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> HTML

HTML DOM History Length Property: ตรวจสอบประวัติการเข้าเยี่ยมชม

คุณสมบัติ history.length คืนค่าจำนวน URL ในรายการประวัติ (History list) ของหน้าต่างเบราว์เซอร์ปัจจุบัน

รูปแบบ (Syntax)

history.length

ตัวอย่างการใช้งาน

แสดงจำนวนรายการในประวัติเมื่อคลิกปุ่ม:

<!DOCTYPE html>
<html>
<head>
    <style>
        body { text-align: center; }
        .btn { background-color: lightblue; border: none; height: 2rem; border-radius: 50px; width: 60%; margin: 1rem auto; display: block; }
        .show { font-size: 2rem; font-weight: bold; color: orange; }
    </style>
</head>
<body>
    <h1>ตัวอย่าง History Length Property</h1>
    <button type="button" onclick="getHistoryLength()" class="btn">คลิกเพื่อดูจำนวนประวัติ</button>
    <div class="show"></div>
    <script>
        function getHistoryLength() {
            var historyLength = history.length;
            document.querySelector(".show").innerHTML = historyLength;
        }
    </script>
</body>
</html>

ข้อจำกัดและความปลอดภัย

  • เข้าถึงได้เฉพาะจำนวนรายการ ไม่สามารถอ่าน URL จริงในประวัติได้ (เพื่อความเป็นส่วนตัว)
  • นับรวมหน้าปัจจุบันด้วย (ค่าต่ำสุดคือ 1)
  • ไม่ทำงานใน iframe ข้ามโดเมน

เมธอดที่เกี่ยวข้อง

เมธอดคำอธิบาย
history.back()กลับไปหน้าก่อนหน้า (เหมือนปุ่ม Back)
history.forward()ไปหน้าถัดไป (เหมือนปุ่ม Forward)
history.go(n)ไปที่รายการในประวัติตามตัวเลข n (ลบ = ย้อนหลัง, บวก = ไปหน้า)