Ruby on Rails AJAX Back button support using Script.aculo.us and Prototype

So I don't really want to get into a debate on 'breaking' the back button with full javascript/AJAX based sites, instead of having pages use regular navigation and only using AJAX within the same page.  Let's just assume you are here because you need to fix the back button for your Rails site after using link_to_remote throughout.  There are a number of solutions out there for various javascript toolkits, but I never was able to find anything that was terribly helpful for Prototype/Scriptaculous.  So I took some of the existing ones out there and adapted them to the Rails environment.

This code uses the same basic methodology as the others out there: manipulating the location bar URL so that it has a hash (#) in it with additional information about the AJAX link which creates back and forward history entries when it is changed. It uses an iframe to support this functionality in IE6 and IE7, otherwise using location.hash manipulation in Firefox, Opera, and Safari 3. A thread (PeriodicalExecuter) is created that checks for changes to the location bar and makes a new Ajax request if needed). Both single step back and forward buttons work, but using the back and forward drop downs will not. Reload/Refresh also works properly, as does Open in New Window/Tab right click and Bookmarks. It simply does normal link_to_remote processing for other browsers, such as old versions of Safari/WebKit (so no history support but the site still works).

The key difference between this method and the others however, is that instead of using some obscure mapping or number for the hash, we simply append all of the Rails controller/action/id?params information after the hash, so if you click an AJAX link http://my.domain.com/controller/action/id?param1=something your location bar will change to http://my.domain.com/#/controller/action/id?param1=something

In the Rails code, you don't always want to have a history/back button entry created for every AJAX call we make, so to differentiate we replace link_to_remote with history_remote whenever we wish to generate a browser history entry. The format is identical, it just adds an extra parameter to the request: history: true. Another key feature to note is that link_to_remote :update => 'some_div' also works with this code (when used as history_remote :update => 'some_div').

///////////////////////////////////////////////////////////
// Slain Jamison Wilde
// This source code is released into the public domain


var PrototypeBackButton = {
    start: function(root, title) {
        this.browser_id = 0;
        this.history_clicks = 0;
        this.ajax_object = null;
        this.history_current_cache = "";
        this.root = root; // this is the initial page we are loading.
        this.title = title;

        is_backable_webkit = false;
        if (Prototype.Browser.WebKit) {
            navigator.userAgent.match(/AppleWebKit\/([^ ]+)/)
            if(parseInt(RegExp.$1) > 420) {
                is_backable_webkit = true;
            }    
        }

        if (Prototype.Browser.IE) {
            this.browser_id = 1;
            var history = $("ie_hash_history");
            var iframe = history.contentWindow.document;
            iframe.open();
            iframe.close();
            iframe.location.hash = location.hash + location.search; // ie breaks up the hash
           this.is_started = true;
           if (location.hash + location.search == "" || location.hash + location.search == "#") {
             new Ajax.Request(root, {asynchronous:true, history:true, evalScripts:true}); 
           }
           this.checker_thread = new PeriodicalExecuter(function() {
             PrototypeBackButton.url_hash_check();
           }, 0.2);  
        } else if (Prototype.Browser.Gecko || Prototype.Browser.Opera || is_backable_webkit == true ) {
          this.browser_id = 2;
          this.is_started = true;
          if (location.hash == "") {      
            new Ajax.Request(root, {asynchronous:true, history:true, evalScripts:true}); 
          }
          this.checker_thread = new PeriodicalExecuter(function() {
              PrototypeBackButton.url_hash_check();
           }, 0.2);  
        } else {
          this.is_started = false;
          new Ajax.Request(root, {asynchronous:true, evalScripts:true}); 
        }
    },

    // Destructor
     destroy: function() {
        this.stop();
    },


     set_root: function(root) {
        this.root = root;
    },

     set_title: function(title) {
        this.title = title;
    },

    stop: function() {
        if (this.checker_thread) { 
            this.checker_thread.stop();
            this.checker_thread = null;
      this.is_started = false;
        }
    },

     url_hash_check: function() {
        if(this.browser_id > 0 && document.title != this.title)
            // hack
            document.title = this.title;
        if (this.browser_id == 1) {
            var history = $("ie_hash_history");
            var iframe = history.contentDocument || history.contentWindow.document;
            var current_hash = iframe.location.hash + iframe.location.search; // ie splits it
            if(current_hash != this.history_current_cache || this.history_clicks > 0) {
        this.history_clicks = 0;
                location.hash = current_hash;
                this.history_current_cache = current_hash;
                if (this.ajax_object) {
                    this.ajax_object.request(current_hash.replace(/^#/, ''));
                    this.ajax_object = null; // dont reuse the request object
                } else {
                    new Ajax.Request(current_hash.replace(/^#/, '')); // reloads dont have an existing object
                }
            }
        } else if (this.browser_id == 2) {
            var current_hash = location.hash;
            if(current_hash != this.history_current_cache || this.history_clicks > 0) {
                this.history_clicks = 0;
                if (this.ajax_object) {
                    this.ajax_object.request(current_hash.replace(/^#/, ''));
                    this.ajax_object = null; // dont reuse the request object
                } else {
                    new Ajax.Request(current_hash.replace(/^#/, ''));  // reloads dont have an existing object
                }
                this.history_current_cache = current_hash;
            }
        }
    },

    ie_history_click: function(hash) {
        var newhash = '#' + hash;
        location.hash = newhash;
        var history = $("ie_hash_history");
        var iframe = history.contentWindow.document;
        iframe.open();
        iframe.close();
        iframe.location.hash = newhash;
    }

}
////////////////////////////////////////////////////////////

You will need to modify the Prototype.js Ajax.Request.request definition to (the changed piece is simply the first 2 conditionals so you should be able to use this with updated Prototype.js versions by moving those pieces into the new version):

  request: function(url) {
        if (PrototypeBackButton.is_started && PrototypeBackButton.browser_id == 1 && this.options.history == true) {
            PrototypeBackButton.ajax_object = this;
            this.options.history = null; // prevent inf loop
            PrototypeBackButton.ie_history_click(url);
            PrototypeBackButton.history_clicks = 1; 
        } else if (PrototypeBackButton.is_started && PrototypeBackButton.browser_id == 2 && this.options.history == true) {
            PrototypeBackButton.ajax_object = this;
            this.options.history = null; // prevent inf loop
            parent.location = '#' + url;
      location.hash = '#' + url
            PrototypeBackButton.history_clicks = 1;
        } else {    
            this.url = url;
            this.method = this.options.method;
            var params = Object.clone(this.options.parameters);

            if (!['get', 'post'].include(this.method)) {
                // simulate other verbs over post
                params['_method'] = this.method;
                this.method = 'post';
            }

            this.parameters = params;

            if (params = Hash.toQueryString(params)) {
                // when GET, append parameters to URL
                if (this.method == 'get')
                    this.url += (this.url.include('?') ? '&' : '?') + params;
                else if (/Konqueror|Safari|KHTML/.test(navigator.userAgent))
                    params += '&_=';
            }

            try {
                if (this.options.onCreate) this.options.onCreate(this.transport);
                Ajax.Responders.dispatch('onCreate', this, this.transport);

                this.transport.open(this.method.toUpperCase(), this.url,
                    this.options.asynchronous);

                if (this.options.asynchronous)
                    setTimeout(function() { this.respondToReadyState(1) }.bind(this), 10);

                this.transport.onreadystatechange = this.onStateChange.bind(this);
                this.setRequestHeaders();

                this.body = this.method == 'post' ? (this.options.postBody || params) : null;
                this.transport.send(this.body);

                /* Force Firefox to handle ready state 4 for synchronous requests */
                if (!this.options.asynchronous && this.transport.overrideMimeType)
                    this.onStateChange();

            }
            catch (e) {
                this.dispatchException(e);
            }
        }
  },

And here is the code for history_remote. Put this into your application_helper.rb. The code as given looks for a global variable $config['enable_back_button'] to determine if it should use the back button code. You can either define this in your environment.rb or simply remove the conditional as needed:

def history_remote(name, options = {}, html_options = {})
    if $config['enable_back_button'] && $config['enable_back_button'] == true
        html_options[:href] = "#" + url_for(options[:url]) # lets 'open in new tab' etc work
        options[:history] = true
        function = remote_function(options);
        function.gsub!(/asynchronous\:true/, 'asynchronous:true, history:true')
#                 logger.dbg function
        link_to_function(name, function, html_options)
    else
        link_to_remote(name, options, html_options)
    end
end

In your layout/application.rhtml, you should add a call to PrototypeBackbutton.start("/controller/action", "My WebPage Title"); The title is there to deal with a bug I never got around to fixing that would keep appending the stuff after the # in the location bar to the title. We just force the title to this instead. You will also need an iframe for IE history:

<iframe id="ie_hash_history" style="display: none;"></iframe>
 

UPDATED: Here is a link to a full Rails 2.0 demo application with all of the pieces. Download the demo. Here is the demo runnning: Live Demo.

This entry was posted on Tue, 15 Jan 2008 03:49:00 GMT and Posted in . You can follow any any response to this entry through the Atom feed. You can leave a comment or a trackback from your own site.
Tags , , , , , , , , , , , ,


Trackbacks

Use the following link to trackback from your own site:
http://blog.slaingod.com/trackbacks?article_id=ruby-on-rails-back-ajax-button-support-using-script-aculo-us-and-prototype&day=14&month=01&year=2008

Comments

Leave a response

  1. goob 27 days later:

    Hello,

    sorry for my english. I have tried your solution, but it don’t work in my environment. The location bar changes after a Ajax-Request and if i press the back button it returns to previous url, but nothing happens. Viz. the page won’t update, just the url. What could be the failure? I think my url looks strange, it should look something like this: http://my.domain.com/#/controller/action

    Here is my url: http://localhost:3000/administration#/administration/index

    after a Ajay-Request: http://localhost:3000/administration#/administration/create_message

    Here the Ajax-Update works. But if i navigate back the updated page remains constant, just url changes to the previous url.

    I hope you can help me.

    regards goob

  2. Slain 28 days later:

    Ok, so in general you should have anything after your http://domain:3000/ before the #. If you are trying to just add backbutton support to your admin section, that should be doable I guess just never tried it.

    Try ensuring that you have a trailing slash before the #? Let me know how that works. Otherwise, I will help you get this going, whatever it takes :)

Leave a comment