JS History ऑब्जेक्ट
In this page:
history.back();
history.forward();
history.go(n);
history.length;
History Object क्या है?
window.history script को current tab की browser session history तक access देता है, जो आपको browser के अपने back/forward buttons पर manual click के बिना user के visited pages में आगे-पीछे जाने देता है।
उदाहरण: What Is the History Object?
console.log(history.length); // number of entries in this tab's session history
// history.back();
// history.forward();
Basic Navigation Methods
history.back() और history.forward() history में किसी भी दिशा में एक step चलते हैं, browser के back/forward buttons के बराबर, जबकि history.go(n) एक साथ कई steps jump कर सकता है (history.go(-2) दो pages पीछे जाता है)।
उदाहरण: Basic Navigation Methods
// history.back(); // like clicking the browser's back button
// history.forward(); // like clicking forward
// history.go(-2); // jump back two pages
console.log(history.length);
History Length जांचना
history.length बताता है कि session history stack में कितनी entries मौजूद हैं, हालांकि privacy कारणों से आप उन entries के असली URLs नहीं पढ़ सकते, सिर्फ count।
उदाहरण: Checking History Length
console.log(history.length); // count only, URLs are private
SPA Navigation के लिए pushState
history.pushState(state, title, url) history में एक नई entry जोड़ता है और बिना page reload trigger किए visible URL बदल देता है, यह वह core mechanism है जिसे single-page apps client-side route changes को असली navigation जैसा दिखाने के लिए इस्तेमाल करते हैं।
उदाहरण: pushState for SPA Navigation
history.pushState({ page: 1 }, "", "?page=1"); // URL changes, no reload
console.log(location.search);
replaceState और popstate Event
history.replaceState() pushState जैसा ही काम करता है पर एक नई entry जोड़ने के बजाय current entry को overwrite करता है, यह बिना back-button step जोड़े किसी URL को ठीक करने के लिए उपयोगी है।
popstate event तब fire होता है जब user back/forward से navigate करता है, जो किसी SPA को history.pushState द्वारा पहले record किए गए किसी भी URL के लिए सही view फिर से render करने देता है।
उदाहरण: replaceState and the popstate Event
history.replaceState({ page: 2 }, "", "?page=2"); // overwrites current entry
window.addEventListener("popstate", (e) => console.log("Navigated:", e.state));
history.pushState()कॉल करना और page के बदलने की उम्मीद करना; यह सिर्फ URL बदलता है।- यह उम्मीद करना कि
pushStateपरpopstatefire होगा, जबकि यह सिर्फ back या forward पर fire होता है। - बिना history के
history.back()इस्तेमाल करना, जहाँ कुछ नहीं होता।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: