Giter VIP home page Giter VIP logo

html5-history-api's Introduction

ENGLISH

This Javascript library provides an emulation of HTML5 History API for older browsers.

The library operates according to W3C specification, adding no new or incompatible methods. The library can be used exactly as described, for example, in Dive Into HTML5 book (http://diveintohtml5.info/history.html) or in the History API Specification (http://www.w3.org/TR/html5/browsers.html#the-history-interface).

You may install this plugin with this command:

npm install html5-history-api

Browser Support:

history.js - IE8+ and other browsers

history.ielte7.js - IE6+ and other browsers

For library developers:

To enable support for HTML5-History-API polyfill in your library, you need to add one line of code:

var location = window.history.location || window.location;

code of library looks like this:

(function(){
  // To enable support for HTML5-History-API polyfill in your library
  var location = window.history.location || window.location;

  // you library code here
  // ....
  // ....
  // ....
})();

AMD Support:

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" src="/require.js"></script>
    <script type="text/javascript">
      requirejs(['/history'], function() {
        if (history.emulate) {
          console.log('In your browser is emulated HTML5-History-API');
        } else {
          console.log('In your browser is natively support HTML5-History-API');
        }
      });
    </script>
  </head>
  <body>
  </body>
</html>

Example of using the library in the pure JS context:

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" src="history.js"></script>
    <script type="text/javascript">
      (function(eventInfo) {
        // we get a normal Location object

        /*
         * Note, this is the only difference when using this library,
         * because the object window.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 "window.location".
         */
        var location = window.history.location || window.location;

        // hang on the event, all references in this document
        document[eventInfo[0]](eventInfo[1] + 'click', function(event) {
          event = event || window.event;
          var target = event.target || event.srcElement;
          // looking for all the links with 'ajax' class found
          if (target && target.nodeName === 'A' &&
             (' ' + target.className + ' ').indexOf(' ajax ') >= 0)
          {
            // keep the link in the browser history
            history.pushState(null, null, target.href);

            // here can cause data loading, etc.

            // do not give a default action
            if (event.preventDefault) {
              event.preventDefault();
            } else {
              event.returnValue = false;
            }
          }
        }, false);

        // hang on popstate event triggered by pressing back/forward in browser
        window[eventInfo[0]](eventInfo[1] + 'popstate', function(event) {

          // here can cause data loading, etc.

          // just post
          alert("We returned to the page with a link: " + location.href);
        }, false);
      })(window.addEventListener ? ['addEventListener', ''] : ['attachEvent', 'on']);
    </script>
  </head>
  <body>
    <a class="ajax" href="/mylink.html">My Link</a>
    <a class="ajax" href="/otherlink.html">Other Link</a>
  </body>
</html>

Example of using the library along with JQuery:

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" src="history.js"></script>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
      $(function() {
        // we get a normal Location object

        /*
         * Note, this is the only difference when using this library,
         * because the object window.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 "window.location".
         */
        var location = window.history.location || window.location;

        // looking for all the links and hang on the event, all references in this document
        $(document).on('click', 'a.ajax', 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).on('popstate', function(e) {

          // here can cause data loading, etc.

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

Advanced library configuration:

history.js?basepath=/pathtosite/ - the base path to the site; defaults to the root "/".
history.js?redirect=true - enable link translation.
history.js?type=/ - substitute the string after the anchor; by default "/".

You can also combine options:

history.js?type=/&redirect=true&basepath=/pathtosite/ - the order of options does not matter.

Or execute special method in JavaScript:

history.redirect(/* type = */ '/', /* basepath = */ '/pathtosite/');

Demo Site: http://history.spb-piksel.ru/ or http://devote.github.io/demos/history/

Follow me on Twitter: https://twitter.com/DimaPakhtinov


РУССКИЙ (Russian)

Библиотека эмулирует HTML5 History API в старых браузерах.

Библиотека, которая не добавляет ненужные методы, заставляя их изучать, а оперирует по спецификации w3c, по интерфейсу History.

Для примера могу привести короткий код как с ней работать.

По принципу мы работаем с HTML5 History API так как описано, например, тут http://htmlbook.ru/html5/history или по спецификации http://www.w3.org/TR/html5/history.html#the-history-interface

Вы можете установить плагин с помощью команды:

npm install html5-history-api

Поддержка браузеров:

history.js - IE8+ и другие браузеры

history.ielte7.js - IE6+ и другие браузеры

Для разработчиков библиотек:

Для включения поддержки плагина HTML5-History-API polyfill в своих библиотеках, добавьте строку кода:

var location = window.history.location || window.location;

код будет выглядеть примерно так:

(function(){
  // Включает поддержку плагина HTML5-History-API polyfill
  var location = window.history.location || window.location;

  // код вашей библиотеки
  // ....
  // ....
  // ....
})();

Поддержка AMD:

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" src="/require.js"></script>
    <script type="text/javascript">
      requirejs(['/history'], function() {
        if (history.emulate) {
          console.log('В вашем браузере эмулируется HTML5-History-API');
        } else {
          console.log('В вашем браузере есть поддержка HTML5-History-API');
        }
      });
    </script>
  </head>
  <body>
  </body>
</html>

Коротенький пример на чистом JS:

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" src="history.js"></script>
    <script type="text/javascript">
      (function(eventInfo) {
        // получаем нормальный объект Location

        /*
         * заметьте, это единственная разница при работе с данной библиотекой,
         * так как объект window.location нельзя перезагрузить, поэтому
         * библиотека history возвращает сформированный "location" объект внутри
         * объекта window.history, поэтому получаем его из "history.location".
         * Для браузеров поддерживающих "history.pushState" получаем
         * сформированный объект "location" с обычного "window.location".
         */
        var location = window.history.location || window.location;

        // вешаем события на все ссылки в нашем документе
        document[eventInfo[0]](eventInfo[1] + 'click', function(event) {
          event = event || window.event;
          var target = event.target || event.srcElement;
          // ищем все ссылки с классом 'ajax'
          if (target && target.nodeName === 'A' &&
             (' ' + target.className + ' ').indexOf('ajax') >= 0)
          {
            // заносим ссылку в историю
            history.pushState(null, null, target.href);

            // тут можете вызвать подгрузку данных и т.п.

            // не даем выполнить действие по умолчанию
            if (event.preventDefault) {
              event.preventDefault();
            } else {
              event.returnValue = false;
            }
          }
        }, false);

        // вешаем событие на popstate которое срабатывает при нажатии back/forward в браузере
        window[eventInfo[0]](eventInfo[1] + 'popstate', function(event) {

          // тут можете вызвать подгрузку данных и т.п.

          // просто сообщение
          alert("We returned to the page with a link: " + location.href);
        }, false);
      })(window.addEventListener ? ['addEventListener', ''] : ['attachEvent', 'on']);
    </script>
  </head>
  <body>
    <a class="ajax" href="/mylink.html">My Link</a>
    <a class="ajax" href="/otherlink.html">Other Link</a>
  </body>
</html>

А теперь показываю пример в связке с jQuery:

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" src="history.js"></script>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
      $(function() {
        // получаем нормальный объект Location

        /*
         * заметьте, это единственная разница при работе с данной библиотекой,
         * так как объект window.location нельзя перезагрузить, поэтому
         * библиотека history возвращает сформированный "location" объект внутри
         * объекта window.history, поэтому получаем его из "history.location".
         * Для браузеров поддерживающих "history.pushState" получаем
         * сформированный объект "location" с обычного "window.location".
         */
        var location = window.history.location || window.location;

        // ищем все ссылки и вешаем события на все ссылки в нашем документе
        $(document).on('click', 'a.ajax', function() {
          // заносим ссылку в историю
          history.pushState(null, null, this.href);

          // тут можете вызвать подгрузку данных и т.п.

          // не даем выполнить действие по умолчанию
          return false;
        });

        // вешаем событие на popstate которое срабатывает при нажатии back/forward в браузере
        $(window).on('popstate', function(e) {

          // тут можете вызвать подгрузку данных и т.п.

          // просто сообщение
          alert("Мы вернулись на страницу со ссылкой: " + location.href);
        });
      });
    </script>
  </head>
  <body>
    <a class="ajax" href="/mylink.html">My Link</a>
    <a class="ajax" href="/otherlink.html">Other Link</a>
  </body>
</html>

Вы можете использовать дополнительные параметры конфигурации библиотеки:

history.js?basepath=/pathtosite/ - базовый путь к сайту, по умолчанию имеет значение корня "/".
history.js?redirect=true - включить преобразование ссылок.
history.js?type=/ - подставлять подстроку после якоря, по умолчанию имеет символ "/".

Также вы можете комбинировать опции:

history.js?type=/&redirect=true&basepath=/pathtosite/ - порядок опций не имеет значение.

Или выполнить специальный метод в JavaScript:

history.redirect(/* type = */ '/', /* basepath = */ '/pathtosite/');

Демо-сайт: http://history.spb-piksel.ru/ или http://devote.github.io/demos/history/

Я в Twitter: https://twitter.com/DimaPakhtinov

html5-history-api's People

Contributors

adesh1997 avatar autowp avatar bjoerge avatar cvazac avatar devote avatar izhyvaiev avatar jarrodek avatar jonscottclark avatar maxmaximov avatar pazams avatar peterdavehello avatar proshin-roman avatar sompylasar avatar vladimirshestakov avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

html5-history-api's Issues

pushState not working on Chrome on IOS 6 (ipad)

When i do a pushState on Chome on ISO6, nothing happens. The native pushState does work (when not loading this library).

I'm trying to debug it myself, but hopefully you can fix it.

I'm having it currently on:
ipad 3 ios 6.0.1
ipad 3 ios 6.1.2
iphone 4 ios 6.1

Broken URLs in IE10 in Windows 7

When I use pushState() in IE10 with a relative URL the final URL in the browser is corrupted. Since IE10 natively supports the native History API I guess there is some problem with version detection.

If I use an absolute path "/yyy/xxx.html" then it works fine, but "xxx.html" doesn't.

When I remove the history.js script from my page the code works fine using the IE10 native API.

tag 4.1.0

history.iegte8.js refers to v 4.1.0 but there's no such tag. It's confusing if you are consuming the lib. When do you plan to tag it?

Tests?

It'd be nice to see that this library had decent test coverage to watch for regressions. It'd be hard for a big company to rely on this library without being confident that updates don't introduce new bugs.

Problem with jQuery 2.0

Hello Dmitrii,

i use our script with jQuery 2.0, but i become an error:

in your script because of the line 431

list[ i ].call( window, o );

in jQuery 2.0 the line 4757

if ( event.target.nodeType === 3 ) {

because the event has no target. Do you have any suggest how to fix this?

Regards,
Marian

broken html5 addEventListener (for case with postMessage usage)

This problem is reproducible only in Fire Fox:
when I trying to send message via Html5 postMessage from iframe (opened e.g. from domain auth.site.com) to main page (on domain site.com) main page didn't get message due to the replacement of the native "addEventListener" method.
In case if i comment out this library\remove addEventListener replacement everything works fine.

Please check this case out.
Thanks in advance.

sessionStorage throws error when cookies are disabled

// this line
var sessionStorage = window['sessionStorage'];

Causes errors when, for whatever reason, cookies are disabled.
This can be because of 'disable cookies' in a development-plugin, or the 'Block third-party cookies and site data' in the Chrome content settings when running the site in a Facebook IFrame.

Calls to window['sessionStorage'] should be wrapped in a try-catch.

Ajax update script error 80020101 with IE

Hello, I'm new here, My problem is when I try to update this script from an ajax response, some like this:

$('head').html(newHeadContent);

I'm using jquery and I'm getting the error 80020101 related to this code in jquery:

globalEval: function( data ) {
if ( data && core_rnotwhite.test( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
}
the problem is with IE only. maybe some problem with the history.min.js code.

wrong name in bower repo

  1. components.json should be renamed to bower.json
  2. When installing this with bower bower install --save html5-history-api it installs as "history" in my local bower.json. This name isn't registered in the bower repo.

Which browsers should it support?

I can't see anywhere which states which browsers that this supports?

I presume that it supports IE8 and IE9? But it would be good to know about others.

npm support

I'm using your library as a dependency in my project and would like to stop copying it across everytime there is an update.
Do you think you could publish HTML5-History-API to npm? (and republish it when you bump the version) npm is full of browser-only libraries these days.

Thanks

Framework should handle Safari's missing history.state

Safari 5.1.5 atleast has no support for history.state, so I'm guessing the older versions does not support it either.
I think the framework itself should handle this, so the use is as easy as it is now.

Works great on all the other browser though, good work! I like it much better than balupton's history.js.

IE detection cc_on causes errors on all IE versions that loads javascript with sourcemaps

Hi,

This single pease of code:
eval("/@cc_on 1;@/")
turns on conditional compiling.

When it is turned on, sourseMapUrl's are executed as code instead of comments and causes runtime errors in IE:
//@ sourceMappingURL=ClipModel.js.map

removing that peace of code seems to fix the errors, and doesn't seem to break anything, but I'm not sure. I guess there is a better way to detect IE.

More information:
http://bugs.jquery.com/ticket/13274

IE9

Все равно пишет что нет метода pushState. Адовый IE... В остальных браузерах все ок и без этой библиотеки
temp

Url changes not as expected in IE8

It works really fine in all browsers, but in IE8 I'm having a few problems with the url redirect. Let me explain:

This is my website url:
http://www.sampleurl.com

And this is the expected url to my campaign:
http://www.sampleurl.com/mycampaign

I know that a hash (#) will appear in IE8, so the expected url is:
http://www.sampleurl.com/#/mycampaign

But, when I access the direct url 'http://www.sampleurl.com/mycampaign' it is changed to:
http://www.sampleurl.com/#!/mycampaign
With an ! after the hash

And this is breaking the correctly functionality of the redirect. Someone has any idea how this can be fixed?

IE11 bug

The same one that was in IE10 and was fixed later: ':///' is added to the address bar.

#7

Mouse wheel click

When the mouse wheel click by link, by usual way it should be open in new tab.
In your code it doesn't.

So i made this possible by few next strings.

// I pass aditional parameter 'e' in function
$("a").click(function(e) {

// make check, if the button equals 1 it means that it's wheel, so open it in new tab.
if( e.button == 1 ) {
window.open( this.href, "_blank" );
return false;
}

// at the end just make sure it's a left button, if it's not - exit of function.
if ( e.button != 0 ) return true;

...

IE6 & IE7 issue - Not working when combined with Modernizr

Thanks for the great polyfill!

I've noticed a strange issue with IE6 and IE7 on XP. If I load Modernizr first, before history.js then things aren't working. Ideally I would like to use Modernizr.load to conditionally load the history.js. My simple test code is below. On IE8 it's fine

DOES NOT WORK

<!DOCTYPE html>
<html>
    <head>
    <script src="modernizr-2.6.2-respond-1.1.0.min.js"></script>        
    <script src="history.js"></script>        
    <script>
    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>

WORKS

<!DOCTYPE html>
<html>
    <head>
    <script src="history.js"></script>        
    <script src="modernizr-2.6.2-respond-1.1.0.min.js"></script>        
    <script>
    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>

Outlook 2010 Web Browser - replaceState function causes loss of focus

http://stackoverflow.com/questions/20099493/using-outlook-2010-as-a-web-browser-the-history-plugin-causes-loss-of-focus

I have provided a little more detail regarding how I use Microsoft Outlook 2010 as my browser in the question above.

Since I wrote the question I have found my issue to be related to the replaceState function in the plugin.

I have programmed my form so that a javascript / jquery keyup function triggers a live search function on my table (datatable). When the keyup function is triggered I also run a function I created called replaceState() which finds all my form inputs and saves the state of them in the history using your plugins history.replaceState function.

Within the Outlook 2010 browser feature each keypress causes the input field to lose focus. I can click back within the field and enter another character but each time the focus is lost. All the functionality works perfectly within this browser and the history is saved successfully.

If I comment out the history.replaceState line the search works fine and doesn't lose focus (and of course doesn't save the history). It doesn't lose focus in IE10 even though the Outlook 2010 browser appears to use the IE10 agent.

Hope you can help with this as I want to integrate my web application into Microsoft Outlook, like Microsoft CRM does.

Thanks for a great plugin, I've tried a few ways to do this and yours is the only one that worked well for me.

forward button greyed out

Hey. In Chrome I noticed the forward button is greyed out.

I went went to page a, page b then back to back a but no forward button to go to back a... Also can I detect if the history API is using pushState or hashes?

SCRIPT126: Specified module could not be found

In IE8 console, I am seeing the following error - and history is not working in IE8:

SCRIPT126: The specified module could not be found.
history.js, line 470 character 21

            // This rule for Internet Explorer 8
            if ('execScript' in window) {
                /**
                 * to IE8 override the global properties using
                 * VBScript, declaring it in global scope with
                 * the same names.
                 */
                <em>window['execScript']('Public ' + prop, 'VBScript')</em>;

(prop = "onhashchange"}

The call stack says this function was called from 'initialize' line 836... which was called by Anonymous line 898 .. then Global code line 16.

It did the same with history.min.js - so switched to full to find the problem lines..

title of chrome history is not correct

If I update document.title before history.pushState, then the google chrome history entry have the title of the page before and not the new title.

I think it is the problem of this code in pushState function:
if (lastTitle != null) {
document.title = lastTitle;
}

inconsistent URL escaping

I am attempting to call history.pushState with a URL that contains escaped JSON data but the behavior is not correct in Firefox. The URL written to the address bar has some escaping removed and no longer works when pasted into a new browser. The problem does not occur in Chrome or IE 9.

history.pushState input URL:

?filters=%5B%7B%22Value%22%3A%22%5BDim%20Date%5D.%5BYear%5D.%26%5B2011%5D%22%2C%22Type%22%3A%22rowFilter%22%2C%22LevelName%22%3A%22%5BDim%20Date%5D.%5BYear%5D.%5BYear%5D%22%2C%22Hierarchy%22%3A%22%5BDim%20Date%5D.%5BYear%5D%22%2C%22CurrentLevel%22%3A%221%22%2C%22TotalLevels%22%3A%221%22%2C%22Text%22%3A%222011%22%7D%2C%7B%22Value%22%3A%22-1%22%2C%22Type%22%3A%22rowFilter%22%2C%22LevelName%22%3A%22%5BDim%20Date%5D.%5BQuarter%5D.%5BQuarter%5D%22%2C%22Hierarchy%22%3A%22%5BDim%20Date%5D.%5BQuarter%5D%22%2C%22CurrentLevel%22%3A%221%22%2C%22TotalLevels%22%3A%221%22%2C%22Text%22%3A%22-1%22%7D%2C%7B%22Value%22%3A%22-1%22%2C%22Type%22%3A%22rowFilter%22%2C%22LevelName%22%3A%22%5BDim%20Date%5D.%5BMonth%5D.%5BMonth%5D%22%2C%22Hierarchy%22%3A%22%5BDim%20Date%5D.%5BMonth%5D%22%2C%22CurrentLevel%22%3A%221%22%2C%22TotalLevels%22%3A%221%22%2C%22Text%22%3A%22-1%22%7D%2C%7B%22Value%22%3A%22Top2Box%22%2C%22Type%22%3A%22TopBoxDropDown%22%2C%22Text%22%3A%22Top2Box%22%7D%2C%7B%22Value%22%3A%22-1%22%2C%22Type%22%3A%22rowFilter%22%2C%22LevelName%22%3A%22%5BDim%20Date%5D.%5BYear%5D.%5BYear%5D%22%2C%22Hierarchy%22%3A%22%5BDim%20Date%5D.%5BYear%5D%22%2C%22CurrentLevel%22%3A%221%22%2C%22TotalLevels%22%3A%221%22%2C%22Text%22%3A%22-1%22%7D%2C%7B%22Value%22%3A%22-1%22%2C%22Type%22%3A%22rowFilter%22%2C%22LevelName%22%3A%22%5BDim%20Date%5D.%5BQuarter%5D.%5BQuarter%5D%22%2C%22Hierarchy%22%3A%22%5BDim%20Date%5D.%5BQuarter%5D%22%2C%22CurrentLevel%22%3A%221%22%2C%22TotalLevels%22%3A%221%22%2C%22Text%22%3A%22-1%22%7D%2C%7B%22Value%22%3A%22-1%22%2C%22Type%22%3A%22rowFilter%22%2C%22LevelName%22%3A%22%5BDim%20Date%5D.%5BMonth%5D.%5BMonth%5D%22%2C%22Hierarchy%22%3A%22%5BDim%20Date%5D.%5BMonth%5D%22%2C%22CurrentLevel%22%3A%221%22%2C%22TotalLevels%22%3A%221%22%2C%22Text%22%3A%22-1%22%7D%2C%7B%22Value%22%3A%22Top2Box%22%2C%22Type%22%3A%22TopBoxDropDown%22%2C%22Text%22%3A%22Top2Box%22%7D%5D&displayType=FullPage

Firefox address bar result:

http://localhost/Win/ameren/report/da435761-5e3c-43fb-8436-e88a24a32eac?filters=[{%22Value%22%3A%22[Dim%20Date].[Year].%26[2011]%22%2C%22Type%22%3A%22rowFilter%22%2C%22LevelName%22%3A%22[Dim%20Date].[Year].[Year]%22%2C%22Hierarchy%22%3A%22[Dim%20Date].[Year]%22%2C%22CurrentLevel%22%3A%221%22%2C%22TotalLevels%22%3A%221%22%2C%22Text%22%3A%222011%22}%2C{%22Value%22%3A%22-1%22%2C%22Type%22%3A%22rowFilter%22%2C%22LevelName%22%3A%22[Dim%20Date].[Quarter].[Quarter]%22%2C%22Hierarchy%22%3A%22[Dim%20Date].[Quarter]%22%2C%22CurrentLevel%22%3A%221%22%2C%22TotalLevels%22%3A%221%22%2C%22Text%22%3A%22-1%22}%2C{%22Value%22%3A%22-1%22%2C%22Type%22%3A%22rowFilter%22%2C%22LevelName%22%3A%22[Dim%20Date].[Month].[Month]%22%2C%22Hierarchy%22%3A%22[Dim%20Date].[Month]%22%2C%22CurrentLevel%22%3A%221%22%2C%22TotalLevels%22%3A%221%22%2C%22Text%22%3A%22-1%22}%2C{%22Value%22%3A%22Top2Box%22%2C%22Type%22%3A%22TopBoxDropDown%22%2C%22Text%22%3A%22Top2Box%22}%2C{%22Value%22%3A%22-1%22%2C%22Type%22%3A%22rowFilter%22%2C%22LevelName%22%3A%22[Dim%20Date].[Year].[Year]%22%2C%22Hierarchy%22%3A%22[Dim%20Date].[Year]%22%2C%22CurrentLevel%22%3A%221%22%2C%22TotalLevels%22%3A%221%22%2C%22Text%22%3A%22-1%22}%2C{%22Value%22%3A%22-1%22%2C%22Type%22%3A%22rowFilter%22%2C%22LevelName%22%3A%22[Dim%20Date].[Quarter].[Quarter]%22%2C%22Hierarchy%22%3A%22[Dim%20Date].[Quarter]%22%2C%22CurrentLevel%22%3A%221%22%2C%22TotalLevels%22%3A%221%22%2C%22Text%22%3A%22-1%22}%2C{%22Value%22%3A%22-1%22%2C%22Type%22%3A%22rowFilter%22%2C%22LevelName%22%3A%22[Dim%20Date].[Month].[Month]%22%2C%22Hierarchy%22%3A%22[Dim%20Date].[Month]%22%2C%22CurrentLevel%22%3A%221%22%2C%22TotalLevels%22%3A%221%22%2C%22Text%22%3A%22-1%22}%2C{%22Value%22%3A%22Top2Box%22%2C%22Type%22%3A%22TopBoxDropDown%22%2C%22Text%22%3A%22Top2Box%22}]&displayType=FullPage

IE9 address bar result:

http://localhost/Win/ameren/report/da435761-5e3c-43fb-8436-e88a24a32eac#/?filters=%5B%7B%22Value%22%3A%22%5BDim%20Date%5D.%5BYear%5D.%26%5B2011%5D%22%2C%22Type%22%3A%22rowFilter%22%2C%22LevelName%22%3A%22%5BDim%20Date%5D.%5BYear%5D.%5BYear%5D%22%2C%22Hierarchy%22%3A%22%5BDim%20Date%5D.%5BYear%5D%22%2C%22CurrentLevel%22%3A%221%22%2C%22TotalLevels%22%3A%221%22%2C%22Text%22%3A%222011%22%7D%2C%7B%22Value%22%3A%22-1%22%2C%22Type%22%3A%22rowFilter%22%2C%22LevelName%22%3A%22%5BDim%20Date%5D.%5BQuarter%5D.%5BQuarter%5D%22%2C%22Hierarchy%22%3A%22%5BDim%20Date%5D.%5BQuarter%5D%22%2C%22CurrentLevel%22%3A%221%22%2C%22TotalLevels%22%3A%221%22%2C%22Text%22%3A%22-1%22%7D%2C%7B%22Value%22%3A%22-1%22%2C%22Type%22%3A%22rowFilter%22%2C%22LevelName%22%3A%22%5BDim%20Date%5D.%5BMonth%5D.%5BMonth%5D%22%2C%22Hierarchy%22%3A%22%5BDim%20Date%5D.%5BMonth%5D%22%2C%22CurrentLevel%22%3A%221%22%2C%22TotalLevels%22%3A%221%22%2C%22Text%22%3A%22-1%22%7D%2C%7B%22Value%22%3A%22Top2Box%22%2C%22Type%22%3A%22TopBoxDropDown%22%2C%22Text%22%3A%22Top2Box%22%7D%2C%7B%22Value%22%3A%22-1%22%2C%22Type%22%3A%22rowFilter%22%2C%22LevelName%22%3A%22%5BDim%20Date%5D.%5BYear%5D.%5BYear%5D%22%2C%22Hierarchy%22%3A%22%5BDim%20Date%5D.%5BYear%5D%22%2C%22CurrentLevel%22%3A%221%22%2C%22TotalLevels%22%3A%221%22%2C%22Text%22%3A%22-1%22%7D%2C%7B%22Value%22%3A%22-1%22%2C%22Type%22%3A%22rowFilter%22%2C%22LevelName%22%3A%22%5BDim%20Date%5D.%5BQuarter%5D.%5BQuarter%5D%22%2C%22Hierarchy%22%3A%22%5BDim%20Date%5D.%5BQuarter%5D%22%2C%22CurrentLevel%22%3A%221%22%2C%22TotalLevels%22%3A%221%22%2C%22Text%22%3A%22-1%22%7D%2C%7B%22Value%22%3A%22-1%22%2C%22Type%22%3A%22rowFilter%22%2C%22LevelName%22%3A%22%5BDim%20Date%5D.%5BMonth%5D.%5BMonth%5D%22%2C%22Hierarchy%22%3A%22%5BDim%20Date%5D.%5BMonth%5D%22%2C%22CurrentLevel%22%3A%221%22%2C%22TotalLevels%22%3A%221%22%2C%22Text%22%3A%22-1%22%7D%2C%7B%22Value%22%3A%22Top2Box%22%2C%22Type%22%3A%22TopBoxDropDown%22%2C%22Text%22%3A%22Top2Box%22%7D%5D&displayType=FullPage

Chrome address bar result:

http://localhost/Win/ameren/report/da435761-5e3c-43fb-8436-e88a24a32eac?filters=%5B%7B%22Value%22%3A%22%5BDim%20Date%5D.%5BYear%5D.%26%5B2011%5D%22%2C%22Type%22%3A%22rowFilter%22%2C%22LevelName%22%3A%22%5BDim%20Date%5D.%5BYear%5D.%5BYear%5D%22%2C%22Hierarchy%22%3A%22%5BDim%20Date%5D.%5BYear%5D%22%2C%22CurrentLevel%22%3A%221%22%2C%22TotalLevels%22%3A%221%22%2C%22Text%22%3A%222011%22%7D%2C%7B%22Value%22%3A%22-1%22%2C%22Type%22%3A%22rowFilter%22%2C%22LevelName%22%3A%22%5BDim%20Date%5D.%5BQuarter%5D.%5BQuarter%5D%22%2C%22Hierarchy%22%3A%22%5BDim%20Date%5D.%5BQuarter%5D%22%2C%22CurrentLevel%22%3A%221%22%2C%22TotalLevels%22%3A%221%22%2C%22Text%22%3A%22-1%22%7D%2C%7B%22Value%22%3A%22-1%22%2C%22Type%22%3A%22rowFilter%22%2C%22LevelName%22%3A%22%5BDim%20Date%5D.%5BMonth%5D.%5BMonth%5D%22%2C%22Hierarchy%22%3A%22%5BDim%20Date%5D.%5BMonth%5D%22%2C%22CurrentLevel%22%3A%221%22%2C%22TotalLevels%22%3A%221%22%2C%22Text%22%3A%22-1%22%7D%2C%7B%22Value%22%3A%22Top2Box%22%2C%22Type%22%3A%22TopBoxDropDown%22%2C%22Text%22%3A%22Top2Box%22%7D%2C%7B%22Value%22%3A%22-1%22%2C%22Type%22%3A%22rowFilter%22%2C%22LevelName%22%3A%22%5BDim%20Date%5D.%5BYear%5D.%5BYear%5D%22%2C%22Hierarchy%22%3A%22%5BDim%20Date%5D.%5BYear%5D%22%2C%22CurrentLevel%22%3A%221%22%2C%22TotalLevels%22%3A%221%22%2C%22Text%22%3A%22-1%22%7D%2C%7B%22Value%22%3A%22-1%22%2C%22Type%22%3A%22rowFilter%22%2C%22LevelName%22%3A%22%5BDim%20Date%5D.%5BQuarter%5D.%5BQuarter%5D%22%2C%22Hierarchy%22%3A%22%5BDim%20Date%5D.%5BQuarter%5D%22%2C%22CurrentLevel%22%3A%221%22%2C%22TotalLevels%22%3A%221%22%2C%22Text%22%3A%22-1%22%7D%2C%7B%22Value%22%3A%22-1%22%2C%22Type%22%3A%22rowFilter%22%2C%22LevelName%22%3A%22%5BDim%20Date%5D.%5BMonth%5D.%5BMonth%5D%22%2C%22Hierarchy%22%3A%22%5BDim%20Date%5D.%5BMonth%5D%22%2C%22CurrentLevel%22%3A%221%22%2C%22TotalLevels%22%3A%221%22%2C%22Text%22%3A%22-1%22%7D%2C%7B%22Value%22%3A%22Top2Box%22%2C%22Type%22%3A%22TopBoxDropDown%22%2C%22Text%22%3A%22Top2Box%22%7D%5D&displayType=FullPage

popstate event completely broken in IE8

In IE8, whenever a call to replaceState or pushState is made, a popState event is dispatched.

Only hash changes not originating from a replace/pushState call should dispatch a popState event.

Add tags for version numbers.

As of now, it is difficult to find the current version of the library, as it is now only written in the different files. You should tag each new version, also making it easier to go back in the version history (great if you are releasing a completely new version, and need to support multiple versions for a while).

Also now, bower.json and package.json is not updated to 4.0.2.

Standard API return value

Hi and thanks for the very nice history api shim !

I wonder however what is the reason to store the data in window.history.location instead of the standard way the API does, using the event object sent to the popstate event handler, that event object having a "state" property with the data associated with the state ?

Issue in IE8

In IE8, when I try to use history.back() to navigate to previous state, it always tells me "Unable to get property 'replace' of undefined or null reference. history.min.js, line 16 character 274" and therefore, the url didn't change to previous state. IE9 & 10 work fine.

IE fallback with multiple parts in the deeplink duplicates the deeplink

Hi,

I'm encountering a wrong behavior when using deeplinks like this in IE 8:
http://localhost:8888/_projects/_libraries/frontend/_svn/skeleton/deploy/public/#/video/1

When doing a push-state with '/video/1' the resulting url is:
http://localhost:8888/_projects/_libraries/frontend/_svn/skeleton-gaia/deploy/public/#/video/video/1
So the first part of the deeplink is repeated. When refreshing and setting the deeplink to that value, the first 2 parts get duplidated.
So in short, everythint except the last part is duplicated.

When stepping trough with breakpoints I located the line that caused the error:

// convert relative link to the absolute
href = /^(?:[\w0-9]+:)?///.test( href ) ?
href.indexOf( "/" ) === 0 ? _protocol + href :
href : _protocol + "//" + current._host + (
href.indexOf( "/" ) === 0 ? href :
href.indexOf( "?" ) === 0 ? _pathname + href :
href.indexOf( "#" ) === 0 ? _pathname + current._search + href :
_pathname.replace( /[^\/]+$/g, '' ) + href
);

At that moment 'href' = "video/1", and _pathname = "/_projects/_libraries/frontend/_svn/skeleton/deploy/public/video/1"
All the checks fail, so it will execute the last part:
_pathname.replace( /[^\/]+$/g, '' ) + href

Here, only '1' is stripped from the _pathname, and video/1 is added, so 'video' is doubled.

I don't know all the situations this line is executed for (different inputs), so I'm not sure how to fix it correctly myself.

If you need more information, or if I have to test something, please let me know.

duplicate URL by IE

Hy,

The problem is, that when the url is: http://...../?s=test/ and then i clicked on a filter, then must the url are ?s=test&order=asc, what in mozilla and other browsers works, but in ie its not work. Here are the urls duplicated like so:

?s=test/?s=test&order=asc

    nohttp   = url.replace("http://","").replace("https://","");
    firstsla = nohttp.indexOf("/");
    pathpos  = url.indexOf(nohttp);
    path     = url.substring(pathpos + firstsla);

    if (push != 1) {
        var stateObj = { foo: 1000 + Math.random()*1001 };

            history.pushState(stateObj, null , path);   

    }

Response over 320k causing an error in Firefox on pushState

I'm running into an odd problem with the library in Firefox.

Initially, it appeared that we had an intermittent problem when calling history.pushState(...), but I've narrowed it down to only occurring when the data I'm trying to push is over 320k in size and I'm using the Firefox browser (v18.0.2). The error I'm getting back from the firebug console is:

NS_ERROR_ILLEGAL_VALUE: Component returned failure code: 0x80070057 (NS_ERROR_ILLEGAL_VALUE) [nsIDOMHistory.pushState]

This same size response causes no problems in either Chrome or IE.

The specific call is:
history.pushState({ tab: tabId, html: data }, reportName, queryString);

where tabId, reportName, & queryString are all trivially short (1, 10, & ~25-30 chars respectively).

The exact same call works fine as long as the data parameter is < 320k. I've experimented with different characters to see if it was some type of encoding issue, but it does not appear to be. I have slowly approached the 320k limit by adding "0"'s to the response and adding that one extra "0" will tip it over the edge and cause the exception.

Has anyone seen this behavior before? Any ideas on workarounds?

Multiple hashes IE9

I have noticed one thing in IE9, after using the page for a while the hash will duplicate see image bellow;

multiple-hashes

history.state in Safari not null

If I change the value in the address bar, then history.state never zero.
In the other browser is the history.state zero.

If I use the back or forward button, then is history.state already filled in all browser.
That is okay.

AMD support

Hi,
it would be nice if there was a little chunk of code added to support AMD interface please

(CommonJS seems not useful since it's a browser only module)

Thanks

Need more Info

My site will support IE8+, and all other modern browsers. I am not passing any additional command line parameters to the script as I am using it. Given that I have a couple of questions.

  1. Do I need this library for older, non-HTML 5 browsers only or should I load it for all browsers?
  2. I have tested on FF and Chrome and it seems to work however for IE8 it does not. I loaded the history.iegte8.js instead of the history.js but I still get errors. Basically it is reporting the history.pushState is not a property or method. There is no documentation but I suspect I only need to load the history.iegte8.js and not both the history.iegte8.js and history.js.

Использование URL якорей (hash) (#)

Нельзя считать единственным способом использования URL-якорей (hash) только для эмуляции работы переходов по страницам и разделам в HTML4 браузерах (например "#/about" для "/about" и "/news/auto" для "news/auto"). Ведь прямое назначения Якорей адреса, это когда он указывает на определённое место на странице (атрибут id html-тега) или указывает скрипту на то, что нужно поменять или сделать на странице, например указывает на определённый таб, или на определённый слайд в презентации или в hash вообще указываются значения выбранных параметров в большой сложной форме поиска (пример: "/search#age=20&political=5"). В последнем случае вообще будет удобно делиться такой ссылкой на определённое состояние формы поиска, а так же иметь удобный способ Prev/Next по истории браузера (состояниям сложной формы поиска).

Для таких случаев возможно лучше было бы иметь возможность в HTML4 браузерах устанавливать только hash с прямым назначением, т. е. когда history.pushState( null, null, "#age=20&political=5"); устанавливал бы такой адрес "{shema+host}{current-url-path}#age=20&political=5". Может какая-то настройка нужна, или передавать дополнительный параметр в pushState.

Но и с автоматическим редиректом (преобразование из HTML4 эмулированного вида в HTML5 вид) тоже стоит немного переобдумать. При вызове редиректа стоит наверно проверить параметр hash на присутствие параметра "type", и делать редирект только в этом случае. Так как якорь может использоваться по своему прямому назначению. Тогда можно было бы поставить параметр type в "!" и не бояться, что будет отредирекчено то, что не должно быть отредерекчино.

history.location.href incorrect in IE9

Hi,
In IE9, the history.location.href is incorrect, but document.location.href is correct, as you can see in the next image:

capture

This always happens whit the first page we browse to, so I think this is because the first page we enter is not saved correctly in the history state.

Any idea how to fix this?
Thanks, and great script by the way!

Установка параметров конфигурации библиотеки

Я так понимаю, что единственный способ установить параметры конфигурации для библиотеки это использовать GET-параметры запроса в адресе на библиотеку: history.js?type={type}&redirect={isRedirect}&basepath={basepath}.

Но как быть, если сервер настроен на установку HTTP-заголовков кеширования файлов без GET-параметров запроса?

И как быть, если есть необходимость упаковывать библиотеку вместе с другими js-библиотеками в один js-файл. Как пример своим сервисом упаковки или сторонним, например: hem, stitch или любые другие.

Для этих случаев не помешало бы иметь альтернативный способ установки конфигурационных параметров.

Ну, и, если представить, что тегов <script> много, то уже немного смущает, то что при инициализации тратится небольшое время на поиск параметров конфигурации.

JSON.parse(null) is invalid (Android 2.3)

There is one issue stopping history.iegte8.js from working with the Android 2.3 stock browser: JSON.parse(null) throws an exception.

This occurs in 1 place in the code:

historyStorage = function(state) {
    return sessionStorage ? state ? sessionStorage.setItem('__hitoryapi__', JSON.stringify(state)) :
        JSON.parse(sessionStorage.getItem('__hitoryapi__')) || {} : {};
},

I see two ways of fixing this:

  1. Inline-resolve: JSON.parse(sessionStorage.getItem('__hitoryapi__') || null)
  2. Use the JSONParse from the IE6-version, but the emulation part is not really needed.

What do you think can one of these fixes be added to history.iegte8.js?
I don't know how you handle it with pull requests, how do you create the minified versions etc.
Please let me know if and how I should create a pull request.

Параметр конфигурации "type"

Я бы предложил параметр конфигурации "type" переименовать в более интуитивно-понятный вид. Вот несколько примеров:

  • hash-prefix
  • prefix
  • hash-delimiter
  • delimiter
  • html4-hash-delimiter
  • hashbang
  • fragment-identifier
  • hash-fragment-identifier

Links with href="/" not working in ie <= 9

The link in the following sample code (with the updated history.js file from github) does not work in Internet Explorer <= 9. Although, if I do not include the history.js it works as expected.

<!doctype html> 
<html>
    <body>
        <a href="/">Homepage</a>
        <script src="history.js"></script>
    </body>
</html>

On the other hand, the following sample code works without problems:

<!doctype html> 
<html>
    <body>
        <a href="/test/">Test</a>
        <script src="history.js"></script>
    </body>
</html>

The problem only appears when we have href="/" in the link.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.