KRUNAL
KRUNAL

Reputation: 81

Why $document.referrer in angular js returning blank. But when i use document.referrer it is returning me value

var referrer = $document.referrer;

Need the value of

$document.referrer 

in a variable.

Upvotes: 5

Views: 8505

Answers (1)

Alex Pollan
Alex Pollan

Reputation: 873

$document is actually a jqLite/jQuery query result soi the property doesn't exists. If you want to get the referrer you can:

a) Access the DOM document directly:

var referrer = document.referrer; 

This is not recommended as you will fall in trouble writing unit tests.

b) Reference the object inside the jqLite/jQuery query result:

var referrer = $document[0].referrer;

Personally I do not like this approach either, the code becomes ugly and misleading.

c) Decorate $document:

myApp.config(function($provide){
  $provide.decorator('$document', function($delegate){

    $delegate.getReferrer = function() {return document.referrer;};

    // alternative you can create a property
    // Object.defineProperty($delegate, 'referrer', {  
    //   get: function() { return document.referrer; }
    // });

    return $delegate; 
  });
});

and then to get the referrer:

var referrer = $document.getReferrer();
//Or if you created a property...
//var referrer = $document.referrer;

I prefer this option because you can easily mock this object in unit tests and your code is easier to understand.

Upvotes: 3

Related Questions