I figured this would have existed out on the web somewhere - but couldn't find it. If you have a page in domain A and want to save a cookie in domain B, this will do it without using 3rd party cookies (which are turned off in many companies).
In addition, one requirement I have is that if the cookie already exists in domain B, it is not changed, bit it is rewritten with it's existing value to restart the clock on it. We use this for tracking people hitting our website. Once we know where they first came from, we do not overwrite that original_referrer value. But we rewrite it so it will not expire.
index.html:
<html>
<head>
<script language="JavaScript"type="text/javascript">
function WriteImage()
{
var html = "http://belle:8080/track/bitmap";
var query = this.location.search.substring(1);
if( query.length > 0 )
html += "?" + query;
document.write("<img src='" + html + "' alt='some text'/>");
}
</script>
</head>
<body>
before
<script language="JavaScript"type="text/javascript">
WriteImage();
</script>
after
</body>
</html>
TrackingBitmap.java:
package net.windward.tracker;
import java.io.*;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.*;
import javax.servlet.http.*;
/**
* fake bitmap for tracking.
*/
@SuppressWarnings({"ForLoopReplaceableByForEach"})
public class TrackingBitmap extends HttpServlet {
byte [] data = null;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
Cookie [] cookies = request.getCookies();
String domain = "." + request.getServerName();
// get the parameters
for (Iterator it=request.getParameterMap().entrySet().iterator(); it.hasNext(); ) {
Map.Entry entry = (Map.Entry) it.next();
String key = (String) entry.getKey();
String [] values = (String[]) entry.getValue();
if (values.length == 0)
continue;
// if have cookie, just re-set it to start the clock ticking again
boolean haveCookie = false;
if (cookies != null)
for (int ind=0; ind<cookies.length; ind++) {
if (cookies[ind].getName().equals(key)) {
Cookie ck = new Cookie(cookies[ind].getName(), cookies[ind].getValue());
if (cookies[ind].getDomain() != null)
ck.setDomain(cookies[ind].getDomain());
ck.setMaxAge(24 * 60 * 60 * 365 * 5);
response.addCookie(ck);
haveCookie = true;
break;
}
}
if (haveCookie)
continue;
// create a cookie
Cookie ck = new Cookie(key, values[0]);
ck.setDomain(domain);
ck.setMaxAge(24 * 60 * 60 * 365 * 5);
response.addCookie(ck);
}
// return a 1x1 image
if (data == null) {
String baseDir = getServletContext().getRealPath("/.");
File file = new File (baseDir, "WEB-INF/empty.gif");
FileInputStream fis = new FileInputStream(file);
data = new byte [fis.available()];
//noinspection ResultOfMethodCallIgnored
fis.read(data);
fis.close();
}
response.setContentLength(data.length);
response.setContentType("image/gif");
OutputStream out = response.getOutputStream();
out.write(data);
out.close();
}
}
Do you find this useful? If so please check out Windward Reports.