Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 759
KRUNAL Avatar asked Oct 19 '22 01:10

KRUNAL


1 Answers

$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.

like image 150
Alex Pollan Avatar answered Nov 15 '22 07:11

Alex Pollan