HTML5 pushState support

519 views
Skip to first unread message

Stefan Asseg

unread,
Jun 28, 2011, 5:43:10 PM6/28/11
to google-we...@googlegroups.com
Is this planned to be included in GWT in the near future or is anyone working on a GWT library that offers HTML5 pushState support?

Nick Hristov

unread,
Jul 1, 2011, 12:04:18 AM7/1/11
to Google Web Toolkit
I just finished writing a barebones support for this:

com/google/gwt/user/client/impl/HistoryStateImpl.java:

package com.google.gwt.user.client.impl;

/**
* History implementation based on pushState
*/
public class HistoryStateImpl extends HistoryImpl {

public native boolean init() /*-{
var token = '';

var path = $wnd.location.pathname;
if (path.length > 0) {
token =
this.@com.google.gwt.user.client.impl.HistoryImpl::decodeFragment(Ljava/
lang/String;)(path);
}

@com.google.gwt.user.client.impl.HistoryImpl::setToken(Ljava/lang/
String;)(token);

var historyImpl = this;

var oldHandler = $wnd.history.onpopstate;

$wnd.onpopstate = $entry(function() {
var token = '';

var path = $wnd.location.pathname;
if (path.length > 0) {
token =
historyImpl.@com.google.gwt.user.client.impl.HistoryImpl::decodeFragment(Ljava/
lang/String;)(path);
}


historyImpl.@com.google.gwt.user.client.impl.HistoryImpl::newItemOnEvent(Ljava/
lang/String;)(token);

if (oldHandler) {
oldHandler();
}
});

return true;
}-*/;

protected native void nativeUpdate(String historyToken) /*-{
var encodedToken =
this.@com.google.gwt.user.client.impl.HistoryImpl::encodeFragment(Ljava/
lang/String;)(historyToken);
$wnd.history.pushState(encodedToken, $wnd.document.title,
encodedToken);
}-*/;
}

In order to get this to work fully, you will have to do some messing
around with Deferred Binding in your module file. Something like this:

<define-property name="history.push.state" values="supported,
notsupported"/>

<property-provider name="history.push.state">
<![CDATA[
if (typeof(window.history.pushState) == "function") {
return "supported";
} else {
return "notsupported";
}
]]>
</property-provider>

<replace-with
class="com.google.gwt.user.client.impl.HistoryStateImpl">
<when-type-is class="com.google.gwt.user.client.impl.HistoryImpl"/>
<all>
<when-property-is name="history.push.state" value="supported"/>
</all>
</replace-with>

What this code will basically do is instead of having hash based
tokens, it will set your url path.

So :

http://www.myserver.com/#foo

becomes

http://www.myserver.com/foo

Note that it will be sensible on the server to be forwarding all
requests into your desired gwt module.
Reply all
Reply to author
Forward
0 new messages