Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set referer for XMLHttpRequest?

I am successfully sending a XMLHttpRequest by using:

var createCORSRequest = function(method, url) {
  var xhr = new XMLHttpRequest();
  if ("withCredentials" in xhr) {
    // Most browsers.
    xhr.open(method, url, true);
  } else if (typeof XDomainRequest != "undefined") {
    // IE8 & IE9
    xhr = new XDomainRequest();
    xhr.open(method, url);
  } else {
    // CORS not supported.
    xhr = null;
  }
  return xhr;
};

var url = 'http://www.whatismyip.com';
var method = 'GET';
var xhr = createCORSRequest(method, url);

xhr.onload = function() {
  // Success code goes here.
};

xhr.onerror = function() {
  // Error code goes here.
};


xhr.setRequestHeader('referer', 'http://www.google.com');
xhr.send();

However, I could not able to define my referer. What is the correct way to add the custom referer?

like image 772
user198989 Avatar asked Nov 30 '14 21:11

user198989


People also ask

How do you set up a referrer URL?

If you want to change the referer (url) header that will be sent to the server when a user clicks an anchor or iframe is opened, you can do it without any hacks. Simply do history. replaceState, you will change the url as it will appear in the browser bar and also the referer that will be send to the server.

How do you set up a Referer policy?

Referrer Policy can be delivered for a request through various methods. It can be done by simply using the HTTP header or the meta element in HTML which takes referrer keyword as value that in turn allows referrer policy setting through markup or using the referrerpolicy content attribute in HTML.

What is URL referrer?

The address of the webpage where a person clicked a link that sent them to your page. The referrer is the webpage that sends visitors to your site using a link. In other words, it's the webpage that a person was on right before they landed on your page.

What is request referrer?

The Referer HTTP request header contains the absolute or partial address from which a resource has been requested. The Referer header allows a server to identify referring pages that people are visiting from or where requested resources are being used.


2 Answers

You cannot. The XMLHttpRequest specification forbids the altering of the referer header (this stops sites lying in it to bypass security checks which some sites use the referer for).

Terminate these steps if header is a case-insensitive match for one of the following headers:

  • Referer
like image 157
Quentin Avatar answered Oct 13 '22 22:10

Quentin


You can try something like this:

xhr.setRequestHeader('X-Referer', window.location.href);

And then read this custom X-Referer header.

like image 23
Babak Avatar answered Oct 14 '22 00:10

Babak