No referer after redirect (Solved)
If you're doing a redirect via HTML, chances are your Firefox and Internet Explorer visitors land on the target page without a referer.
Meta Redirect
<meta http-equiv="refresh" content="0; URL=/target-page"/>
- Good: Safari and Opera will set the referer to the current page
- Bad: Firefox and Internet Explorer will submit an empty referer
JavaScript Redirect
<script> window.location.href = '/target-page' </script>
- Good: Safari, Opera and Firefox will set the referer to the current page
- Bad: Internet Explorer will submit an empty referer
Best Solution
Use a header redirect. All browsers will preserve the referer.
HTML Solution (using JavaScript)
If you can't set a header redirect, make a JavaScript form submit:
<form action="/target-page" method="get" name="redirect"></form>
<script> document.forms['redirect'].submit() </script>
All browsers will set the referer to the current page.
Written by Robert Wünsch
Related protips
7 Responses
THANK YOU! This was very helpful for me :)
For some reason, this was dropping query params. When I made action="/target-page?foo=bar"
, the requested URL was /target-page?
. I have no idea why.
Have you tried adding the parameters as <input hidden>?
Not sure what you mean. You mean adding the parameters as form inputs? I did not try that, but it's a great idea... I'd have to parse the URI and loop through params. I might try it.
Yeah adding the query params as inputs works. It's a bit tedious but I think it will be the most robust solution.
The other thing I was trying was to generate a link and then find it and call .click()
on it. It worked pretty well but I was worried it wouldn't be supported by all browsers.
First of all, thanks!
Secondly, regarding passing variable as inputs I did it something like this and works perfectly:
<!DOCTYPE html>
<html>
<body>
<form action="<?php echo $_GET['action']; ?>" method="get" name="redirect">
<?php foreach ($_GET as $key => $value) { ?>
<?php if ($key != 'action') { ?>
<input type="hidden" name="<?php echo $key; ?>" value="<?php echo $value; ?>" />
<?php } ?>
<?php } ?>
</form>
<script> document.forms['redirect'].submit() </script>
</body>
</html>
Pure JS redirect.
var redirect = function(url) {
var dom = window.document.createElement('form');
var parts = url.split('?');
var url_ = parts[0], params = parts[1] || '';
var paramlist = params.split('&');
dom.setAttribute('method', 'get');
dom.setAttribute('action', url_);
dom.style.display = 'none';
dom.style.visibility = 'hidden';
var e, kv, k, v;
for (var i = 0; i < paramlist.length; ++i) {
kv = paramlist[i].split('=');
k = kv[0];
v = kv[1];
e = window.document.createElement('input');
e.setAttribute('type', 'hidden');
e.setAttribute('name', decodeURIComponent(k));
e.setAttribute('value', decodeURIComponent(v));
dom.appendChild(e);
}
window.document.body.appendChild(dom);
dom.submit();
}