All blog posts, code samples and downloads licensed under Apache License 2.0.
Close

Return to the last viewed XPage using cookies

Oliver Busse on 03/18/2013 01:59:42 CET, filed under SSJS XSP 

Brad Balassaitis and Don McNally discussed this topic in their blogs several days ago: how to return to the last viewed XPage after e.g. a document's "save and close" or "close" action? In that case you might want to return to the page that displayed the document you just edited in a view panel or something like that.

That inspired me to post my solution. In all other posts the last page name was stored in a session-scoped variable. My solutions differs from that as I use cookies.

// put this into a custom control like "ccLastPage"

<?xml version="1.0" encoding="UTF-8"?>
<xp:view
	xmlns:xp="http://www.ibm.com/xsp/core">
	<xp:this.beforePageLoad><![CDATA[#{javascript:var pageURL = facesContext.getExternalContext().getRequest().getRequestURI();
var qs = facesContext.getExternalContext().getRequest().getQueryString();
setCookie("_lastPage", session.evaluate("@RightBack(\"" + pageURL + "\"; \"/\")").get(0) + (qs != "" ? "?"+qs:""), 7)}]]></xp:this.beforePageLoad>
</xp:view>

// store this code in the SSJS library called "cookiehandling"

// get a cookie value server side
function getCookie(cookieName){
	var c = facesContext.getExternalContext().getRequestCookieMap().get(cookieName)
	return (c!=null)?c.getValue():""
}

// set a cookie value server side
// give the name, the value and the expires value in days
function setCookie(cookiename, cookieval, expires){
	response = facesContext.getExternalContext().getResponse(); 
	userCookie = new javax.servlet.http.Cookie(cookiename, cookieval);
	if(expires) userCookie.setMaxAge(expires*24*60*60*1000); 
	response.addCookie(userCookie); 
}

Usage:

Place the custom control on every page that you want to return to in that way. When the page loads the script stores the page name in a cookie named "_lastPage". If you want to return to that page from another page just create a script action in e.g. a button that calls the getCookie() method to calculate the page name to open.

The benefit of this one is that the page name is stored even if you log out or close your browser. It depends on how long you store the cookie by setting the 3rd parameter of the setCookie() method. As you can see you can set any numeric value - it will be interpreted as the number of days. Use 0 to store it indefinitely in your browser's cookie store.

There are of course many ways to calculate the current page's name, but this one does it for me Winken

If you are interested in the two other posts, here you go:

http://xcellerant.net/2013/03/15/return-to-last-view/

http://dmcnally.blogspot.dk/2013/03/xpages-returning-to-prior-page.html


Tagged with cookies custom controls