Home > Java > JSF view scope with multiple tabs using JavaScript and sessionStorage

JSF view scope with multiple tabs using JavaScript and sessionStorage

JSF applications often use view scope for server-side state. While that is convenient it can be problematic to handle multiple browser tabs. The backend has no way of knowing which tab the user is working with. The session cookie is global for the entire browser and any URL
parameters or hidden parameters will be copied to new tabs. What to do? And even worse, what to do when you have to live with an ancient version of JSF (2.0 in our case)?

It is fairly easy to write a custom view scope on the server side, been there done that a few times. In order to pick the right beans it needs to identify the active tab. The browser will not help us, so as usual these days we must resort to JavaScript.

My first idea was to use the sessionStorage attribute. Add a script to the top of every page that looks for a window id in the sessionStorage. If it is found, add a hidden field with it to all forms in the loaded page, register a click handler that prevents navigation from links and sets the location manually with the id appended as a query parameter, override window.open in order to append the id as a query parameter in that case as well and finally register a ajaxPrefilter handler with jQuery in order to intercept AJAX requests and add the id as a request header. Oh, and rewrite the history in order to remove the id from the browser’s address line as well.

Combined with a servlet filter that denies requests that lack the window id by returning a short JavaScript function that sets it and retries this worked well – in Chrome. Internet Explorer was not as helpful. According to the specification:

When a new top-level browsing context is created by cloning an existing browsing context, the new browsing context must start with the same session storage areas as the original, but the two sets must from that point on be considered separate, not affecting each other in any way.

The major browsers diverge in how they interpret that. To cut things short my cunning plan failed.

Fortunately there is an attribute that is unique across browser tabs: window.name! I changed the code to store the unique id in window.name instead and voila! It worked.

Lesson learned – as usual the browsers can be trusted not to be consistent. Take care with sessionStorage.

Advertisements
Categories: Java
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: