Эмулировать / polyfill history.pushstate () в IE - PullRequest
42 голосов
/ 08 июля 2011

history.pushstate() не поддерживается в IE.Есть ли другой способ добиться этого в IE?

Ответы [ 2 ]

28 голосов
/ 08 июля 2011

Рассмотрите возможность использования или адаптации History.js из GitHub. Согласно описанию:

History.js изящно поддерживает API истории / состояния HTML5 (pushState, replaceState, onPopState) во всех браузеры. Включая постоянную поддержку для данных, заголовков, replaceState. Поддерживает jQuery, MooTools и Прототип. Для браузеров HTML5 это означает, что вы можете изменить URL напрямую, без необходимости использования больше хэшей Для браузеров HTML4 это вернется к использованию старого Функциональность onhashchange.

IE (до 9 включительно), не поддерживает pushstate (). IE 10 поддерживает это.

http://caniuse.com/#search=pushstate

17 голосов
/ 27 февраля 2012

Рассмотрите возможность использования History API для неподдерживаемых браузеров или посмотрите библиотеку на https://github.com/devote/HTML5-History-API

Эта библиотека Javascript обеспечивает эмуляцию HTML5 History API для старых браузеров.

Библиотека работает в соответствии со спецификацией W3C, не добавляя новые или несовместимые методы. Библиотеку можно использовать в точности так, как описано, например, в книге «Погружение в HTML5» http://diveintohtml5.info/history.html или в спецификации API истории http://www.w3.org/TR/html5/history.html#the-history-interface.

Пример использования библиотеки в чистом JS-контексте:

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="history-2.0.4.js"></script>
        <script type="text/javascript">
            window.onload = function() {

                // function for the reference is processed
                // when you click on the link
                function handlerAnchors() {
                    // keep the link in the browser history
                    history.pushState( null, null, this.href );


                    // here can cause data loading, etc.


                    // do not give a default action
                    return false;
                }

                // looking for all the links
                var anchors = document.getElementsByTagName( 'a' );

                // hang on the event, all references in this document
                for( var i = 0; i < anchors.length; i++ ) {
                    anchors[ i ].onclick = handlerAnchors;
                }

                // hang on popstate event triggered
                // by pressing back/forward in browser
                window.onpopstate = function( e ) {

                    // we get a normal Location object

                    /*
                    * Note, this is the only difference when using this library,
                    * because the object document.location cannot be overriden, so
                    * library the returns generated "location" object within an
                    * object window.history, so get it out of "history.location".
                    * For browsers supporting "history.pushState" get generated
                    * object "location" with the usual "document.location".
                    */
                    var returnLocation = history.location || document.location;


                    // here can cause data loading, etc.


                    // just post
                    alert( "We returned to the page with a link: " +
                                                         returnLocation.href );
                }
            }
        </script>
    </head>
    <body>
        <a href="/mylink.html">My Link</a>
        <a href="/otherlink.html">Other Link</a>
    </body>
</html>

Пример использования библиотеки вместе с JQuery:

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="history-2.0.4.js"></script>
        <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript">
            $(function() {

                // looking for all the links and hang on the event,
                // all references in this document
                $("a").click(function() {
                    // keep the link in the browser history
                    history.pushState( null, null, this.href );


                    // here can cause data loading, etc.


                    // do not give a default action
                    return false;
                });

                // hang on popstate event triggered
                // by pressing back/forward in browser
                $( window ).bind( "popstate", function( e ) {

                    // we get a normal Location object

                    /*
                    * Note, this is the only difference when using this library,
                    * because the object document.location cannot be overriden, so
                    * library the returns generated "location" object within an
                    * object window.history, so get it out of "history.location".
                    * For browsers supporting "history.pushState" get generated
                    * object "location" with the usual "document.location".
                    */
                    var returnLocation = history.location || document.location;


                    // here can cause data loading, etc.


                    // just post
                    alert( "We returned to the page with a link: " +
                                                        returnLocation.href );
                });
            });
        </script>
    </head>
    <body>
        <a href="/mylink.html">My Link</a>
        <a href="/otherlink.html">Other Link</a>
    </body>
</html>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...