Skip to content

Instantly share code, notes, and snippets.

@debprado
Forked from nragaz/rails.history.js
Created January 3, 2012 19:04
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save debprado/1556365 to your computer and use it in GitHub Desktop.
Save debprado/1556365 to your computer and use it in GitHub Desktop.
Add callbacks to remote links in Rails to manage browser history using pageState and replaceState
function historySupport() {
return !!(window.history && window.history.pushState !== undefined);
}
function pushPageState(state, title, href) {
if (historySupport()) {
history.pushState(state, title, href);
}
}
function replacePageState(state, title, href) {
if (state == undefined) { state = null; }
if (historySupport()) {
history.replaceState(state, title, href);
}
}
$(function() {
window.onpopstate = function(e) {
if ($('body').attr('data-state-href') === location.href) {
return false;
}
if (e.state !== null) {
// do something with your state object
}
$.ajax({
url: location.href,
dataType: 'script',
success: function(data, status, xhr) {
$('body').trigger('ajax:success');
},
error: function(xhr, status, error) {
// You may want to do something else depending on the stored state
alert('Failed to load ' + location.href);
},
complete: function(xhr, status) {
$('body').attr('data-state-href', location.href);
}
});
};
var getA = 'a[data-remote][data-method!="put"][data-method!="post"][data-method!="delete"]'
, getForm = 'form[data-remote][method="get"]';
function getState(el) {
// insert your own code here to extract a relevant state object from an <a> or <form> tag
// for example, if you rely on any other custom "data-" attributes to determine the link behaviour
return {};
};
$('body').attr('data-state-href', location.href);
$(getA).
live('ajax:beforeSend', function(xhr) {
pushPageState(getState(this), "Loading...", this.href);
window.title = "Loading...";
});
$(getForm).
live('ajax:beforeSend', function(xhr) {
var href = $(this).attr("action") + "?" + $(this).serialize();
pushPageState(getState(this), 'Loading...', href);
window.title = "Loading...";
});
$(getA + ',' + getForm).
live('ajax:complete', function(xhr) {
$('body').attr('data-state-href', location.href);
replacePageState(getState(this), window.title, location.href);
});
});
@briarsweetbriar
Copy link

This is great, but are you also having a problem with the referrer being set to the current URL?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment