Skip to content

Instantly share code, notes, and snippets.

@seanadkinson
Last active August 29, 2015 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seanadkinson/a53e6ae23b345c95ef7c to your computer and use it in GitHub Desktop.
Save seanadkinson/a53e6ae23b345c95ef7c to your computer and use it in GitHub Desktop.
React-Router History.js Location
"use strict";
/**
* Location provider for react-router that uses History.js to
* provide HTML5 History API-like functionality for older browsers
* such as IE 7-9.
*
* This file:
* - Uses webpack and the script-loader to include History.js
* - Assumes you have historyjs installed in node_modules
*
* To use:
* var HistoryJSLocation = require('path/to/HistoryJSLocation');
*
* And then in react-router 0.10 and below:
* <Router.Routes location={HistoryJSLocation}>
*
* Or for react-router 0.11 and after:
* Router.run(routes, HistoryJSLocation, function (Handler) { ... }
*
*/
require('script!historyjs/scripts/uncompressed/history.js');
require('script!historyjs/scripts/uncompressed/history.html4.js');
require('script!historyjs/scripts/uncompressed/history.adapter.native.js');
var _onChange;
function getCurrentUrl() {
var currentUrl = History.getState().url;
var rootUrl = History.getRootUrl();
var path = '/' + currentUrl.substr(rootUrl.length);
var hashIndex = path.indexOf('#');
if (hashIndex !== -1) {
path = path.substr(hashIndex+1);
}
if (path.charAt(0) === '.') {
path = path.substr(1);
}
if (path.charAt(0) !== '/') {
path = '/' + path;
}
return path;
}
function onStateChange() {
_onChange({
type: 'pop',
path: getCurrentUrl()
});
}
/**
* A Location that uses History.js
*/
var HistoryJSLocation = {
setup: function (onChange) {
_onChange = onChange;
if (window.addEventListener) {
window.addEventListener('statechange', onStateChange, false);
} else {
window.attachEvent('onstatechange', onStateChange);
}
},
teardown: function () {
if (window.removeEventListener) {
window.removeEventListener('statechange', onStateChange, false);
} else {
window.detachEvent('onstatechange', onStateChange);
}
},
push: function (path) {
console.log("Pushing: " + path);
History.pushState(null, null, path);
_onChange({
type: 'push',
path: getCurrentUrl()
});
},
replace: function (path) {
History.replaceState(null, null, path);
_onChange({
type: 'replace',
path: getCurrentUrl()
});
},
pop: function () {
History.back();
},
getCurrentPath: getCurrentUrl,
toString: function () {
return '<HistoryJSLocation>';
}
};
module.exports = HistoryJSLocation;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment