DhtmlHistory (+ bug en IE7)
dhtmlHistory
DhtmlHistory es un interesante mini framework para simular el comportamiento del botón “Atrás” en aplicaciones web realizadas con AJAX, desarrollado por Brad Neuberg.
En la página del autor podeis encontrar varios ejemplos de funcionamiento junto a una explicación mas detallada, así como descargaros la última versión.
Error en IE7
A continuación un caso curioso que me ha acontecido recientemente usando DhtmlHistory junto a IE7.
Estamos desarrollando una aplicación web con AJAX que requería controlar el botón “Atrás”. En IE7 experimentaba un comportamiento extraño al cambiar estilos dinámicamente, siempre que tenían que ver con ocultar o mostrar partes de la página. El efecto era que la página se desplazaba o centraba en la venta aleatóriamente.
Finalmente pudimos comprobar que eliminando el javascript dhtmlHistory.js el efecto no se producía. Centrados en el objeto de error nos dimos cuenta gracias al DOM Explorer Toolbar que el HTML se estaba generando incorrectamente, con todo el código HTML en la etiqueta HEAD y únicamente con un TEXTAREA en el BODY:

Al eliminar el dhtmlHistory.js, el HTML se generaba corréctamente. Supongo que, pese a que renderizaba bien el HTML generado por incorrecto que fuese (recuperación de errores lo llaman), cuando se aplicaban estilos de manera dinámica se hacía incorrectamente al encontrarse en el HEAD.
La solución
La solución es sencilla: generar el HTML necesario una vez que la página se ha cargado, para lo que se han modificado los métodos init() y create() en dhtmlHistory.js:
init():
/** private */ init: function() {
// write a hidden form into the page
var styleValue = "position: absolute; top: -1000px; left: -1000px;";
if (this.debugging == true) {
styleValue = "width: 30em; height: 30em;";
}
var newContent =
"<form id='historyStorageForm' "
+ "method='GET' "
+ "style='" + styleValue + "'>"
+ "<textarea id='historyStorageField' "
+ "style='" + styleValue + "'"
+ "left: -1000px;' "
+ "name='historyStorageField'></textarea>"
+ "</form>";
document.body.innerHTML+=newContent; // CHANGED:
this.storageField = document.getElementById("historyStorageField");
},
create():
/** private */ create: function() {
// get our initial location
var initialHash = this.getCurrentLocation();
// save this as our current location
this.currentLocation = initialHash;
// write out a hidden iframe for IE and
// set the amount of time to wait between add() requests
if (this.isInternetExplorer()) {
var aux = "<iframe style='border: 0px; width: 1px; "
+ "height: 1px; position: absolute; bottom: 0px; "
+ "right: 0px; visibility: visible;' "
+ "name='DhtmlHistoryFrame' id='DhtmlHistoryFrame' "
+ "src='blank.html?" + initialHash + "'>"
+ "</iframe>";
document.body.innerHTML+=aux; // CHANGED
// wait 400 milliseconds between history
// updates on IE, versus 200 on Firefox
this.WAIT_TIME = 400;
}
Y finalmente, mover la inicialización que hay al final del fichero al manejador de carga de la página, en nuestro caso:
Event.observe(window, 'load', init_page, false);
function init_page(){
/* Initialize dhtmlHistory*/
window.historyStorage.init();
window.dhtmlHistory.create();
}
Actualización [28.feb.2007]
La solución que aporta Stefan Gustafsson en los comentarios es bastante más secilla y además funciona en IE 5. Consiste en mover la inicialización al final de la página, os la recomiendo.
Que aproveche.
Esta entrada fué escrita el Martes, 23 Enero 2007 a las 5:08 y etiquetada con Desarrollo Web. Puedes seguir lo comentarios en el feed RSS 2.0. Deja tu comentario, o traza desde tu sitio web.


6 comentarios a “DhtmlHistory (+ bug en IE7)”
Vaya tela, eh?
Bien por compartir
(Sorry for not writing in spanish)
Your solutions does not work with F5 (page-refresh) since IE does not preserve the values of the
form fields if the textarea field is generated to late.
I solved the problem by moving the code:
from the end of dhtmlHistory.js and added them to the bottom of my page.
Thx Stefan!
Without doubt a better solution!
You are welcome.
I forgot to mention you also need to make sure page caching work correctly for F5 to work as expected. I write about it in a post in my new blog.
http://expisoft.blogspot.com/2007/03/history-reloaded.html
Hi guys,
I’m new to AJAX and javascript, I’ve been using Ajaxtabs from:
http://www.dynamicd rive.com/ dynamicindex17/ ajaxtabscontent/ index.htm
When I found out about AJAX behavior about not keeping state while
moving with the browsers back and forward button, searching I came
across Brad’s Neuberg, Really Simple History for AJAX:
http://www.onjava. com/pub/a/ onjava/2005/ 10/26/ajax- handling- bookmarks-
and-back-button. html?page= 1
The issue here is that haven’t been able to get it right, if I choose
the tab with id=”salary” then the content is loaded ok, no problem
there AJAX magic works fine, but now, if I navigate to a different
web address and then press the back button all I get on the browsers
address bar is ;
http://localhost/ #section:
I think it should be http://localhost/ #section: salary right?
So the tabs state is lost, defaulting to the original state as if I
first loaded the page and the intro tab (id=”intro”) appears
selected, can anyone help me? show me the correct way to do this
using the above tools, a real example would be great using these 2
tools.
Thanks
Funcionou muito bem no meu site, parabéns.
Tu comentario
Se requieren los campos indicados. El email nunca se publica o distribuye.
Puedes usar algo de HTML:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>Las URIs deben esta cualificadas (ej: http://www.nombredominio.com) y las etiquetas cerradas convenientemente.
Los párrafos y saltos de línea se convierten automágicamente.