Your post title shows that you want to change the current page programmatically using JavaScript but still having the HTTP referrer provided (from what I understood, using a <a>
tag is just for a test case).
You need to be aware of cross-browser issues:
- The HTTP referrer header (HTTP-Referer) is set when changing
window.location.href
under the following browsers:- MSIE 9 (but probably any version above 9)
- Firefox (at least 3.0, 3.5, 4.0, 5.0, but most probably all versions)
- Chrome (at least 9, but most probably all versions)
- Safari (at least 5, but most probably all versions)
- Opera (at least 11, but most probably all versions)
- MSIE (at least 6, 7, 8): the referrer is not set when changing
window.location.href
(this is why some pseudo-solutions are based onmyLink.click()
) - Firefox (at least 3.0, 3.5, 4.0): the
click
function does not exist (this is why pseudo-solutions based onmyLink.click()
do not work) - Firefox 5 : the
click
function exists under Firefox 5 but does not
change the window location, so all the methods relying on the
existence of themyLink.click()
method will not work. CallingmyLink.onclick()
ormyLink.onClick()
raise an error (“onclick is not a function”), so solutions based on these calls will not work.
In order to manage these cross-browser issues, I’m using the following method:
function navigateToUrl(url) {
var f = document.createElement("FORM");
f.action = url;
var indexQM = url.indexOf("?");
if (indexQM>=0) {
// the URL has parameters => convert them to hidden form inputs
var params = url.substring(indexQM+1).split("&");
for (var i=0; i<params.length; i++) {
var keyValuePair = params[i].split("=");
var input = document.createElement("INPUT");
input.type="hidden";
input.name = keyValuePair[0];
input.value = keyValuePair[1];
f.appendChild(input);
}
}
document.body.appendChild(f);
f.submit();
}
navigateToUrl("http://foo.com/bar");
This solution works on all the browser flavors and version listed above. It has the advantage to be simple, multi-browser and easy to understand.
Note that this has not been tested under HTTPS.