I have sorted out a case where referrer is lost in various page jump methods. It is mentioned that in IE, when a page is redirected using a method like location.href = "a.html", the value of document.referrer in the target page will be empty. This should be a bug in IE.
In most cases, this problem will not cause us trouble, but sometimes we have to use JavaScript to jump, and at the same time we have to collect document.refer on the next page, so we have to think of other ways.
Form GET method
The first thing that comes to mind is to use Form form to initiate a GET request using JS. The code looks like this:
The code copy is as follows:
function goToPage(url) {
if (isIE) {
// IE browser
var frm = document.createElement("form");
frm.action = url;
frm.method = "GET";
document.body.appendChild(frm);
frm.submit();
} else {
// Non-IE
location.href = url;
}
}
This method can work as expected, and document.referrer in the target page can point to the previous page normally.
A-element simulation click method
After searching online, I found that Situ Zhengmei's blog recorded another way to deal with this problem:
The code copy is as follows:
//define for all browsers
function goto(url) {
location.href = url;
}
//re-define for IE
if (isIE) {
function goto(url) {
var referLink = document.createElement('a');
referLink.href = url;
document.body.appendChild(referLink);
referLink.click();
}
}
The principle is very simple. First create an A element, specify its href attribute as the target link, and then use JS to trigger its click event. After testing, document.referrer can also be retrieved normally on the target page.
The code of this method is shorter and should be better than the above solution using form forms.