How to manually set REFERER header in Javascript?
Asked Answered
D

9

78

I want to set Referer header of my webpage. Currently it displays "xyz" and I want to set it to "abc".

Viewed referer using javascript:alert(document.referer)

Decasyllable answered 6/3, 2012 at 9:0 Comment(6)
This has been asked before: #220731Distribution
@TiesonT. Actually, that question is about accessing HTTP headers, not about overriding the Referer header.Ideomotor
@MathiasBynens Fair enough, but you can't change something you can't access, right? :)Distribution
You can't, document.referrer is a read-only property, which value changes only when picking a link. If this picked link is on a security site, an empty string is assigned.Expel
@T.J.Crowder Both reasons :) Forgetting to accept answers sometimes and sometimes I do not get acceptable answersDecasyllable
So there is no way to edit a site Referer object?Decasyllable
H
37

You cannot set Referer header manually but you can use location.href to set the referer header to the link used in href but it will cause reloading of the page.

Hohenstaufen answered 7/3, 2012 at 8:3 Comment(3)
thanks it changes the referer but it changes the URL of selenium server So i consider that it is impossible to change the refererDecasyllable
@Hohenstaufen Any chance you can write a bit more about how your answer materializes in code? E.g. a short javascript snipping or HTML snippet?Hydrastinine
@jsmcfrind A bit late, but if you just do window.location.reload() this will cause the page to reload and if you check document.referrer it should be equal to the current page instead of whatever it may have been before. Tried creating a test case in jsfiddle but failed because of the sandbox nature of the website. (Though I did create a somewhat amusing recursive jsfiddle in the process.)Clop
J
63

You can use Object.defineProperty on the document object for the referrer property:

Object.defineProperty(document, "referrer", {get : function(){ return "my new referrer"; }});

Unfortunately this will not work on any version of safari <=5, Firefox < 4, Chrome < 5 and Internet Explorer < 9 as it doesn't allow defineProperty to be used on dom objects.

Jonejonell answered 2/5, 2014 at 18:47 Comment(5)
Works also. Prefer this to @casivaagustin's answer though his works alsoBrodeur
With this method I get an error in Safari 9: "TypeError: Attempting to change the getter of an unconfigurable property."Ledezma
If you want to change it in tests and want to redifine the referrer in multiple test cases, use ``` Object.defineProperty(document, 'referrer', { configurable: true, get: () => url, }); ```Shadshadberry
It sets the object property but isn't set in request headersBiome
Noob here. Would this line go inside <script/>? Is it to be called within an event like onload or document.ready?Unshod
H
37

You cannot set Referer header manually but you can use location.href to set the referer header to the link used in href but it will cause reloading of the page.

Hohenstaufen answered 7/3, 2012 at 8:3 Comment(3)
thanks it changes the referer but it changes the URL of selenium server So i consider that it is impossible to change the refererDecasyllable
@Hohenstaufen Any chance you can write a bit more about how your answer materializes in code? E.g. a short javascript snipping or HTML snippet?Hydrastinine
@jsmcfrind A bit late, but if you just do window.location.reload() this will cause the page to reload and if you check document.referrer it should be equal to the current page instead of whatever it may have been before. Tried creating a test case in jsfiddle but failed because of the sandbox nature of the website. (Though I did create a somewhat amusing recursive jsfiddle in the process.)Clop
C
27

This works in Chrome, Firefox, doesn't work in Safari :(, haven't tested in other browsers

        delete window.document.referrer;
        window.document.__defineGetter__('referrer', function () {
            return "yoururl.com";
        });

Saw that here https://gist.github.com/papoms/3481673

Regards

test case: https://jsfiddle.net/bez3w4ko/ (so you can easily test several browsers) and here is a test with iframes https://jsfiddle.net/2vbfpjp1/1/

Cliftonclim answered 10/7, 2014 at 11:5 Comment(4)
but how about when a user tries to access a new site ??? for example there is a link on site1.com that redirect user on site2.comSpermiogenesis
doesn't add referral domain "yoururl.com"Hector
@Brandito It didn't work, the value has changed, but when you send a request such as image, you can find the referrer is still the old one.Forefoot
I can confirm it works in Safari 13. But I had to use location.reload(); afterwards.Ieper
F
13

I think that understanding why you can't change the referer header might help people reading this question.

From this page: https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name

From that link:

A forbidden header name is the name of any HTTP header that cannot be modified programmatically...

Modifying such headers is forbidden because the user agent retains full control over them.

Forbidden header names ... are one of the following names:

...

Referer

...

Forefather answered 9/8, 2018 at 19:20 Comment(0)
T
4

You can not change the REFERRER property. What you are asking is to spoof the request.

Just in case you want the referrer to be set like you have opened a url directly or for the fist time{http referrer=null} then reload the page

location.reload();
Thunderstruck answered 15/5, 2016 at 9:33 Comment(2)
this only remove referrer header. doesn't add custom headerHector
Right. the question isnt about adding the custom header.Thunderstruck
P
3

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.

Place answered 28/10, 2017 at 22:53 Comment(1)
You can only replace the path or add-remove fragments, not the domain with history.replaceState. developer.mozilla.org on history.replaceStateAbram
D
2

Above solution does not work for me , I have tried following and it is working in all browsers.

simply made a fake ajax call, it will make a entry into referer header.

var request;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
    request = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
    try {
        request = new ActiveXObject('Msxml2.XMLHTTP');
    } catch (e) {
        try {
            request = new ActiveXObject('Microsoft.XMLHTTP');
        } catch (e) {}
    }
}
request.open("GET", url, true);
request.send();
Dame answered 14/12, 2015 at 7:34 Comment(1)
how i should try this ? can you please provide me steps for this as i used many ways to change referrar header but nothing works ?Hector
I
0

You can change the value of the referrer in the HTTP header using the Web Request API.

It requires a background js script for it's use. You can use the onBeforeSendHeaders as it modifies the header before the request is sent.

Your code will be something like this :

    chrome.webRequest.onBeforeSendHeaders.addEventListener(function(details){
    var newRef = "http://new-referer/path";
    var hasRef = false;
    for(var n in details.requestHeaders){
        hasRef = details.requestHeaders[n].name == "Referer";
        if(hasRef){
            details.requestHeaders[n].value = newRef;
         break;
        }
    }
    if(!hasRef){
        details.requestHeaders.push({name:"Referer",value:newRef});
    }
    return {requestHeaders:details.requestHeaders};
},
{
    urls:["http://target/*"]
},
[
    "requestHeaders",
    "blocking"
]);

urls : It acts as a request filter, and invokes the listener only for certain requests.

For more info: https://developer.chrome.com/extensions/webRequest

Incomplete answered 6/9, 2017 at 12:23 Comment(4)
any chance of a better example? where am i suppose to paste this?Benoite
You are supposed to create a background script and paste it in that file. Be sure to add the file as a background script in your manifest.Incomplete
This answer is valid if you are writing a chrome extension. - If your clients / users accepts to install it - Or if you are doing something at home for your own use and ready to install your own extension.Kalinin
This is not working now. Perhaps earlier work. But now there is no referer header in details.requestHeaders list untill request pushed. So it is not possible to change it like thatCoumas
B
0

If you need to set it from google or any other website that links to your website and be sure, google or that website is the referrer value, you may follow these instructions:

  1. Go to google.com
  2. Type site:mywebsiteexample.com
  3. After finding it, right click and inspect
  4. On the top right of the screen, you may find a cursor to select what part of the DOM you want to select and inspect. Select the anchor. Modify the href value to the link you want. Then hit enter.

After clicking the anchor, it should redirect to your link or page and the referrer value should be in this case from google.com or the website you've decided

Bootlick answered 4/1, 2023 at 6:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.