Как настроить смартфоны и ПК. Информационный портал

Js история браузера. Введение в HTML5 History API

Если вам никогда раньше не приходилось встречаться с объектом history, не стоит волноваться по этому поводу. До сих пор он не мог предложить нам ничего полезного. В действительности, традиционный объект history имеет только одно свойство и три основных метода. Это свойство length - содержит информацию о количестве элементов в списке истории просмотров (т.е. в поддерживаемом браузером списке недавно посещенных веб-страниц). Вот пример использования этого свойства:

Alert("У вас сохранено " + history.length + " страниц, в истории браузера.");

History.back();

Эффект этого метода равнозначен нажатию пользователем кнопки браузера "Назад". Подобным образом можно использовать метод forward() для перемещения на один шаг вперед или метод go() для перехода вперед или назад на определенное количество шагов.

Но все это не представляет большой ценности, если только вы не хотите создать для веб-страницы собственные кнопки "Назад" и "Вперед". Но HTML5 добавляет этому объекту history несколько дополнительных возможностей, которые можно использовать для реализации намного более амбициозных задач.

Главной из этих возможностей является метод pushState() , который позволяет изменить URL в адресной строке браузера, не обновляя при этом содержимого страницы. Эта возможность приходится кстати в специфической ситуации, а именно при создании динамических страниц, которые незаметно загружают новое содержимое и плавно обновляют себя. В такой ситуации URL страницы и ее содержимое могут рассогласоваться.

Например, если страница загрузит в динамическом режиме содержимое с другой страницы, первоначальный URL страницы не изменится, что может вызвать разнообразные проблемы с созданием закладки для этой страницы. Эту проблему можно решить с помощью отслеживания истории сеансов.

Если вы пока не видите, как это сделать не переживайте, в следующем разделе мы рассмотрим страницу, идеально подходящую для применения истории просмотров.

16 ответов

Короткий ответ: вы не можете.

Технически существует точный способ проверки подлинности:

History.previous

Однако это не сработает. Проблема в том, что в большинстве браузеров это считается нарушением безопасности и обычно просто возвращает undefined .. p >

History.length

Это свойство, которое другие предложили...
Однако длина не работает полностью, поскольку в истории вы не указываете , где . Кроме того, он не всегда начинается с того же номера. Например, браузер, не настроенный на целевую страницу, начинается с 0, тогда как другой браузер, который использует страницу перевязки, начинается с 1.

History.back();

History.go(-1);

и он просто ожидал, что если вы не сможете вернуться, то щелчок по ссылке ничего не делает.

Мой код позволяет браузеру вернуться на одну страницу, и если это не удается, он загружает резервный URL-адрес. Он также обнаруживает изменения хэштегов.

Если кнопка "Назад" недоступна, резервный url будет загружен через 500 мс, поэтому браузер имеет достаточно времени для загрузки предыдущей страницы. Загрузка обратного URL сразу после window.history.go(-1); приведет к тому, что браузер будет использовать резервный URL-адрес, потому что js script еще не остановился.

Function historyBackWFallback(fallbackUrl) { fallbackUrl = fallbackUrl || "/"; var prevPage = window.location.href; window.history.go(-1); setTimeout(function(){ if (window.location.href == prevPage) { window.location.href = fallbackUrl; } }, 500); }

это похоже на трюк:

Function goBackOrClose() { window.history.back(); window.close(); //or if you are not interested in closing the window, do something else here //e.g. theBrowserCantGoBack(); }

Вызов history.back(), а затем window.close(). Если браузер сможет вернуться в историю, он не сможет перейти к следующему утверждению. Если он не сможет вернуться, он закроет окно.

Однако, обратите внимание, что если страница была достигнута, набрав URL-адрес, то firefox не позволит script закрыть окно.

Вы не можете напрямую проверить, доступна ли кнопка "Назад". Вы можете посмотреть history.length>0 , но это будет верно, если страницы впереди и на текущей странице. Вы можете только быть уверены, что кнопка "Назад" непригодна, если history.length===0 .

Если это не достаточно хорошо, обо всем, что вы можете сделать, это позвонить history.back() и, если ваша страница все еще загружена, кнопка "Назад" недоступна! Конечно, это означает, что если кнопка "Назад" доступна, вы просто перешли от страницы. Вам не разрешено отменять навигацию в onunload , поэтому обо всем, что вы можете сделать, чтобы остановить обратное на самом деле, это вернуть что-то из onbeforeunload , что приведет к появлению большого раздражающего приглашения. Это не стоит.

На самом деле обычно это действительно плохая идея делать что-либо с историей. Навигация по истории - для браузера Chrome, а не для веб-страниц. Добавление ссылок "вернуться" обычно вызывает больше недоумения пользователей, чем это стоит.

Вот как я это сделал.

Я использовал событие "beforeunload" , чтобы установить логическое значение. Затем я установил тайм-аут, чтобы посмотреть, запускается ли "beforeunload".

Var $window = $(window), $trigger = $(".select_your_link"), fallback = "your_fallback_url"; hasHistory = false; $window.on("beforeunload", function(){ hasHistory = true; }); $trigger.on("click", function(){ window.history.go(-1); setTimeout(function(){ if (!hasHistory){ window.location.href = fallback; } }, 200); return false; });

Кажется, он работает в основных браузерах (тестировал FF, Chrome, IE11 до сих пор).

В моих проектах есть фрагмент:

Function back(url) { if (history.length > 2) { // if history is not empty, go back: window.History.back(); } else if (url) { // go to specified fallback url: window.History.replaceState(null, null, url); } else { // go home: window.History.replaceState(null, null, "/"); } }

К вашему сведению: я использую History.js для управления историей браузера.

Зачем сравнивать history.length с номером 2?

Потому что стартовая страница Chrome считается первым элементом в истории браузера.

Существует несколько возможностей history.length и поведения пользователя:

  • Пользователь открывает новую пустую вкладку в браузере, а затем запускает страницу. history.length = 2 и мы хотим отключить back() в этом случае, потому что пользователь перейдет на пустую вкладку.
  • Пользователь открывает страницу в новой вкладке , щелкая ссылку где-то раньше. history.length = 1 и снова мы хотим отключить метод back() .
  • И, наконец, пользователь попадает на текущую страницу после перезагрузки нескольких страниц . history.length > 2 и теперь back() можно включить.

Примечание: я пропускаю случай, когда пользователь попадает на текущую страницу после нажатия на ссылку с внешнего сайта без target="_blank" .

Примечание 2: document.referrer пуст, когда вы открываете веб-сайт, вводя его адрес, а также когда веб-сайт использует ajax для загрузки подстраниц, поэтому я прекратил проверку этого значения в первом случае.

history.length бесполезен, так как он не показывает, может ли пользователь вернуться в историю. Также разные браузеры используют начальные значения 0 или 1 - это зависит от браузера.

Рабочее решение - использовать событие $(window).on("beforeunload" , но я не уверен, что он будет работать, если страница загружается через ajax и использует pushState для изменения истории окна.

Итак, я использовал следующее решение:

Var currentUrl = window.location.href; window.history.back(); setTimeout(function(){ // if location was not changed in 100 ms, then there is no history back if(currentUrl === window.location.href){ // redirect to site root window.location.href = "/"; } }, 100);

Будьте осторожны с window.history.length потому что оно также содержит записи для window.history.forward()

Таким образом, вы можете иметь window.history.length с более чем 1 записями, но без записей истории. Это означает, что ничего не произойдет, если вы запустите window.history.back()

Я придумал следующий подход. Он использует событие onbeforeunload, чтобы определить, покидает ли браузер страницу или нет. Если в определенный промежуток времени он не будет перенаправлен на резервную копию.

Var goBack = function goBack(fallback){ var useFallback = true; window.addEventListener("beforeunload", function(){ useFallback = false; }); window.history.back(); setTimeout(function(){ if (useFallback){ window.location.href = fallback; } }, 100); }

Вы можете вызвать эту функцию, используя goBack("fallback.example.org") .

window.location.pathname выдаст вам текущий URI. Например, https://domain/question/1234/i-have-a-problem выдаст /question/1234/i-have-a-problem . См. Документацию о window.location

Затем вызов функции split() даст нам все фрагменты этого URI. поэтому, если мы возьмем наш предыдущий URI, у нас будет что-то вроде ["", "question", "1234", "i-have-a-problem"] . См. Документацию о String.prototype.split() для получения дополнительной информации.

Вызов filter() здесь для того, чтобы отфильтровать пустую строку, созданную обратной косой чертой. Он будет возвращать только фрагмент URI, длина которого больше 1 (непустая строка). Таким образом, у нас будет что-то вроде ["question", "1234", "i-have-a-question"] . Это можно было бы написать так:

"use strict"; window.location.pathname.split("/").filter(function(fragment) { return fragment.length > 0; });

См. Документацию о Array.prototype.filter() и назначении Destructuring для получения дополнительной информации.

Теперь, если пользователь пытается вернуться, находясь на https://domain/ , мы не будем запускать оператор if и поэтому не window.history.back() вызывать метод window.history.back() чтобы пользователь оставался на нашем веб-сайте. Этот URL будет эквивалентен который имеет длину 0 , а 0 > 0 - false. Следовательно, молча терпит неудачу. Конечно, вы можете что-то зарегистрировать или выполнить другое действие, если хотите.

"use strict"; function previousPage() { if (window.location.pathname.split("/").filter(({ length }) => length > 0).length > 0) { window.history.back(); } else { alert("You cannot go back any further..."); } }

Ограничения

Конечно, это решение не будет работать, если браузер не поддерживает History API . Проверьте документацию, чтобы узнать больше об этом, прежде чем использовать это решение.

До появления HTML5 единственное, что мы не могли контролировать и управлять (без перезагрузки контента или хаков с location.hash) - это история одного таба. С появлением HTML5 history API все изменилось - теперь мы можем гулять по истории (раньше тоже могли), добавлять элементы в историю, реагировать на переходы по истории и другие полезности. В этой статье мы рассмотрим HTML5 History API и напишем простой пример, иллюстрирующий его возможности.

Основные понятия и синтаксис History API опирается на один DOM интерфейс - объект History. Каждый таб имеет уникальный объект History, который находится в window.history . History имеет несколько методов, событий и свойств, которыми мы можем управлять из JavaScript. Каждая страница таба(Document object) представляет собой объект коллекции History. Каждый элемент истории состоит из URL и/или объекта состояния (state object), может иметь заголовок (title), Document object, данные форм, позиция скролла и другую информацию, связанную со страницей.

Основные методы объекта History:

  • window.history.length: Количество записей в текущей сессии истории
  • window.history.state: Возвращает текущий объект истории
  • window.history.go(n) : Метод, позволяющий гулять по истории. В качестве аргумента передается смещение, относительно текущей позиции. Если передан 0, то будет обновлена текущая страница. Если индекс выходит за пределы истории, то ничего не произойдет.
  • window.history.back() : Метод, идентичный вызову go(-1)
  • window.history.forward() : Метод, идентичный вызову go(1)
  • window.history.pushState(data, title [, url]) : Добавляет элемент истории.
  • window.history.replaceState(data, title [, url]) : Обновляет текущий элемент истории
  • Для перехода на 2 шага назад по истории можно использовать:
    history.go(-2)
    Для добавления элементов истории мы можем использовать history.pushState:
    history.pushState({foo: "bar"}, "Title", "/baz.html")
    Для изменения записи истории мы можем использовать history.replaceState:
    history.replaceState({foo: "bat"}, "New Title") Живой пример Теперь мы знаем основы, давайте посмотрим на живой пример. Мы будем делать веб файловый менеджер, который позволит вам найти URI выбранного изображения(). Файловый менеджер использует простую файловую структуру, написанную на JavaScript. Когда вы выбираете файл или папку картинка динамически обновляется.

    Мы используем data-* атрибуты для хранения заголовка каждой картинки и используем свойство dataset для получения этого свойства:

  • crab2.png

  • Чтобы все работало быстро мы подгружаем все картинки и обновляем атрибут src динамически. Это ускорение создает одну проблему - оно ломает кнопку назад, поэтому вы не можете переходить по картинками вперед или назад.

    HTML5 history приходит на помощь! Каждый раз когда мы выбираем файл создается новая запись истории и location документа обновляется (оно содержит уникальный URL картинки). Это означает, что мы можем использовать кнопку назад для обхода наших изображений, в то время как в строке адреса у нас будет прямая ссылка на картинку, которую мы можем сохранить в закладки или отправить кому-либо.

    Код У нас есть 2 дива. Один содержит структуру папок, другой содержит текущую картинку. Все приложение управляется с помощью JavaScript. В будут освещены только самые важные моменты. Исходный код примера очень короткий (порядка 80 строк) посмотрите его после прочтения всей статьи.

    Метод bindEvents навешивает обработчики для события popstate , который вызывается, когда пользователь переходит по истории и позволяет приложению обновлять свое состояние.
    window.addEventListener("popstate", function(e){ self.loadImage(e.state.path, e.state.note); }, false);
    Объект event , который передается в обработчик события popstate имеет свойство state - это данные, которые мы передали в качестве первого аргумента pushState или replaceState .

    Мы навешиваем обработчик на событие click на див, который представляет нашу файловую структуру. Используя делегацию событий, мы открываем или закрываем папку или загружаем картинку (с добавлением записи в историю). Мы смотрим на className родительского элемента для того, чтобы понять на какой из элементов мы нажали:
    - Если это папка мы открываем или закрываем её
    - Если это картина, то мы показываем её и добавляем элемент истории

    Dir.addEventListener("click", function(e){ e.preventDefault(); var f = e.target; // Это папка if (f.parentNode.classList.contains("folder")) { // Открываем или закрываем папку self.toggleFolders(f); } // Это картинка else if (f.parentNode.classList.contains("photo")){ note = f.dataset ? f.dataset.note: f.getAttribute("data-note"); // отрисовываем картинку self.loadImage(f.textContent, note); // добавляем элемент истории history.pushState({note: note, path:f.textContent}, "", f.textContent); } }, false);
    Метод, который изменяет содержимое картинки и обновляет её подпись очень прост:
    loadImage: function(path, note){ img.src = path; h2.textContent = note; }
    Мы получили простое приложение , демонстрирующее возможности обновленного интерфейса объекта History . Мы используем pushState для добавления элемента истории и событие popstate для обновления содержимого страницы. Кроме этого при клике на картинку мы получаем в адресной строке её действительный адрес, который мы можем сохранить или отправить кому-нибудь.

    Когда можно будет использовать? Firefox 4+
    Safari 5+
    Chrome 10+
    Opera 11.5+
    iOS Safari 4.2+
    Android 2.2+
    IE ???
    Список браузеров , поддерживающих history API

    Until recently, we developers couldn’t to do much with the state and history of the browser. We could check the number of items in the history and push users forwards and backwards, but this provides little benefit to the user. With the rise of more dynamic web pages, we need more control. Thankfully, HTML5 gives us that control by extending the JavaScript History API.

    What’s the point?

    It goes without saying that URLs are important. They’re the method of accessing the vast collections of information and resources on the web, and more recently, they’ve begun representing the intended state of a web application. You can copy these URLs and share them with your friends or use them to create links from any HTML document. They’re the veins of the web, and the y need to be looked after.

    Previously, the JavaScript History API offered some very simple functionality:

    // Check the length of the history stack console.log(history.length); // Send the user agent forward console.log(history.forward()); // Send the user agent back console.log(history.back()); // Send the user agent back (negative) or forward (positive) // by a given number of items console.log(history.go(-3));

    With dynamic Ajax web applications, where the browser updates the page in parts instead of changing location entirely, it’s difficult to give the user a URL to bookmark or share the current application state. Fragment identifiers , like those used on this article’s headings via the id attribute, provide some state information, but they’re entirely dependent on client-side scripts.

    Save this file and open it in your favourite editor. It must be accessed via HTTP, so that means you need either a local server (e.g. http://localhost/) or an online web server you can upload to. Viewing the file directly using your browser’s Open File function will not work , since it uses the file:// protocol and not HTTP. Also be sure to update the href attributes on each of the navigation links to ensure the correct directory structure is used. Personally, I’m viewing the demo locally at http://localhost/history .

    We’ll be working exclusively within the element at the end of the . The code includes some simple styles and dynamically changes the content as you click the links. In reality, this could be loaded from your server via XMLHttpRequest , but for the purposes of this demonstration I’ve bundled it up into a self-contained file. The important part is that we have a quick-and-dirty dynamic page to work with, so let the fun begin!

    At the moment there, is no bookmarkable URL for the different states of this page. If you click around the navigation items, then click Back in your browser, you won’t be taken back to the previous state and may even be taken away from the page to whatever you viewed before (depending on your browser). It would be nice if you could share “Socks” with your friends, right? We can do that via history.pushState() .

    The history.pushState() method takes three parameters:

    Data Some structured data, such as settings or content, assigned to the history item. title The name of the item in the history drop-down shown by the browser’s back and forward buttons. (Note: this is not currently supported by any major browsers.) url (optional) The URL to this state that should be displayed in the address bar.

    With these parameters, you can define the state of the page, give that state a name, and even provide a bookmarkable address, as if the page had reloaded entirely. Let’s dive right in and add this to the clickHandler function, right above the return statement:

    Function clickHandler(e) { /* Snip... */ // Add an item to the history log history.pushState(data, event.target.textContent, event.target.href); return event.preventDefault(); }

    The single line of code we added informs the history object that:

    • we want to add an item to the log,
    • it should remember the data that we’ve already loaded,
    • it should assign a name to this state based on the text of the link we clicked (even though this isn’t used - it’s good to get into the habit of recording a name for the state), and
    • it should update the address bar with the href attribute of that link.

    Reload the page in your browser and click a few of the links, keeping an eye on the address bar. Notice how it changes on each click, despite the fact that you aren’t actually navigating away from this page. If you also have a look at your history log, you’ll see a long list of page titles (in this case ”Kittens!” over and over). Provided your server is set up to serve the correct page upon access, the user could copy that URL and paste it into a new browser window to jump straight to that kitten.

    At the moment, clicking the back button will pop you through the history items, but the page won’t react to these changes. That’s because so far, we’ve only created the history records. How can we allow active users to return to a previous state? We listen to the popstate event.

    Historical Events in Navigation

    The user agent fires a popstate event when the user navigates through their history, whether backwards or forwards, provided it isn’t taking the user away from the current page. That is, all those pushState s we called will keep the user on the current page, so the popstate event will fire for each history item they pop through.

    Before the closing tag, add a new listener for the popstate event:

    // Revert to a previously saved state window.addEventListener("popstate", function(event) { console.log("popstate fired!"); updateContent(event.state); });

    We attach the event listener to the window , which is responsible for firing the event, and pass this event into our handler. We log a message (so we can see when this event is firing), and then we update the content using the state we saved previously. The state is attached to the event object via the state property.

    Open up the page fresh in your browser, click around like before, and then click back. As before, the URL in the address bar changes as you cycle through states, but now the content is also restored back to what it should be. Click forward, and the content is likewise correctly restored.

    If you look at the developer console in Chrome when you load the page for the first time, you’ll see the popstate event fired immediately, before you’ve even clicked a link. This is because Chrome considers the initial page load to be a change in state, and so it fires the event. In this instance, the state property is null , but thankfully the updateContent function deals with this. Keep this in mind when developing as it could catch you out, especially if other browsers assume this behavior.

    Rewriting history

    Unfortunately, as fantastic as HTML5 is, it doesn’t allow us actual time travel. If it did, I would be going back to my childhood and telling a younger me, “Yes, you should have a slice of cake”. Take that as you will.

    The History API does, however, allow us to make amends to our history log items. For example, we could update the current state in response to fresh user input in a form. We can do this with history.replaceState .

    replaceState works just as pushState does, with the exact same parameters, except that it updates the current entry instead of adding a new one. I can think of one situation in our demo where this could be used: the initial page load. If you click back for long enough, you’ll find that going back to the original URL doesn’t provide you the original content. Let’s fix that by adding the following to the bottom of our script:

    // Store the initial content so we can revisit it later history.replaceState({ content: contentEl.textContent, photo: photoEl.src }, document.title, document.location.href);

    As this runs when the page loads, it saves the initial page state. We can later load this state when the user browses back to this point via the event listener we set up previously. You can try it out by loading up the page, clicking a few links, and then hitting back until you return to the original URL. The initial content has returned!

    Demo

    I’ve set up a demo of our completed code. I’ve also added a little back-end magic to make our history.pushState URLs work like a real site. Remember that the URLs you push should be live URLs that the user can bookmark and share as real entry points to your site.

    Browser support

    Up-to-date copies of Chrome (5+), Safari (5.0+), Firefox (4.0+), and Opera (11.50+) have support for the new History API. Even some mobile browsers work just fine, like Mobile Safari on iOS 4+. Unfortunately, IE 9 and below lack support, but it when it arrives.

    Safari 5.0 sometimes exhibits one oddity: navigating between states causes the loading spinner to appear and stay even when the state has been loaded. This stops when you navigate away using a link or action that does not involve a state saved by the History API.

    Polyfill

    A polyfill does exist for the History API. The aptly named History.js uses HTML4’s hashchange event with document fragment identifiers to mimic the history API in older browsers. If one of the hash URLs is used by a modern browser, it uses replaceState to quietly correct the URL.

    It sounds like magic, but make sure you’re aware of the consequences of using fragment identifiers, as mentioned previously in this article. As such, the author of History.js has put together a guide titled Intelligent State Handling .

    Closing thoughts

    URLs go beyond just the browsing session of a user. They’re historically important markers for resources that could very well remain in use for many years to come. Before you embark on developing your site’s JavaScript, you should give thought to the design of your URLs . Make them meaningful and organised. Make sure you can directly access them without JavaScript. Only then should you add your JavaScript to enhance the browsing experience.

    • Category
    26 Responses on the article “Pushing and Popping with the History API”

    I literally *just* discovered this and worked on this for a client two weeks ago. I even contemplated writing a blog about it because of how cool I found this. This really can be a game changer.

    I’m surprised you did not cover the history.state feature? I believe this is the current spec, though it only works in Firefox. The code used here, while it does work, I thought was part of the original version of the spec. Also, worth mentioning is that you are *supposed* to pass in JavaScript object like in your example. Microsoft’s IE blog has examples where a string is passed in. I’ve not tested support on this across browsers, but it’s worth mentioning.

    I literally cannot tell you how many hours the whole “Store the initial content so we can revisit it later” issue turned out to be an issue for me. It seems unintuitive to me that the default state that you come to is not in the history stack.

    I’m trying the demo page on Internet Explorer 9 and I can’t tell any difference to Chrome so it seems to work.

    I’ll be using this article for a future project, for sure. Thank you!

    thank you for sharing your experience, very informative.

    Could you please elaborate on what you did on the server to handle the fake URLs? Are they manual redirects you inserted, or automatic rewrites? How are they converted?

    Thank you so much!

    In the mean time, I advanced a bit on that same subject. If your web server is Apache, you can configure it to use mod_rewrite, which allows to convert user (or crawler) typed URLs into other server side URLs:

    This is done by adding a number of rules in the .htaccess at the root of your website.

    Literally, just released my new site which makes use of this technique. It works beautifully!

    It’s nice to (maybe) be able to do away with hashes and hashbangs on future ajax-based sites.

    I’m really looking forward to seeing how this gets used as it’s adopted more widely.

    The only issues arise (as is often the case) with cross-browser implementations of this. The history API may be supported by the browsers you mentioned but with varying degrees of success.

    Check out History.js (note the capital ‘H’) by Ben Lupton here:https://github.com/balupton/History.js/ which offers a means to use HTML5 history states while accounting for craoos browser inconsistencies.

    Again, great article. Really gets down to the underlying principles.

    This is great, but if it doesn’t work on IE9 or below it’s pretty useless for production sites currently (without lots of messy hacks and fallbacks!)

    @Raphael + Eric:

    My apologises for the late reply! For the purposes of the demo, I used a very basic mod_rewrite and PHP setup.

    RewriteRule ^(fluffy|socks|whiskers|bob)$ index.php?p=$1

    The above rewrite rule masks the demo URLs and passes it into a single PHP file with a query string of what cat the user is attempting to view. The PHP file then checks $_GET["p"] is valid (always sanitise and check your input as appropriate), then using the pre-defined variables I have set for that cat.

    If this were a real application, the requested path could be used to construct database queries (sanitised of course) to pull in more dynamic content. CMS like WordPress use something like this for their “clean URL” implementation.

    Hope this helps.

    Would it be possible to see that htaccess file closer. I understand everything going on here, within the history api part, except the mod_rewrite. Do you actually have more pages living somewhere for each of these different cats? Refreshing the page after you click a few of the cats returns a page not found error. This has to do with the htaccess part that I am missing, right? Thanks.

    Despite my comment above about poor browser support I decided to switch from hashed URLs (/#/slug) to HTML5 history for http://goproheroes.com and decided to just fall back to normal page loading for IE9 and below using:

    function supports_history_api() {
    return !!(window.history && history.pushState);
    }

    Thanks Mike, your demo helped me out. I had my attempt a bit more complicated than it needed to be.

    However, I’m trying to track and detect when the user steps forward and back through the history so I can add appropriate transitions to my page. Unfortunately, the history API doesn’t let you know if a forward or back button was clicked on a popstate event. That would be really helpful.

    I’m thinking that a cookie might be the only way to attempt to track the order. Saving a previous variable in the state object complicated things and caused browser issues.

    Adding to the list,
    thanks Mike!

    Those adorable kitten’s helped me setup some pushing and popping functions on the soon-to-be released new version of my site!

    Thanks for the tut!

    In your clickhandler function you have something wrong in your post code (it’s ok on kittieland though):

    1. The event object is declared on the arguments as “e”, not “event”.

    2. There is no updateContent(); anywhere! I had to check your working source to see if I was doing something wrong.

    But wait, there’s more! …some updates too:

    3. Chrome 19+ starts to mingle with the state property of the event and stuff.

    As a tip: I used a lame setTimeout() to bind the event listener in order to skip Chrome’s eagerness to pop its state.

    Лучшие статьи по теме