Why $ document.referrer in angular js returns empty. But when I use document.referrer, it returns me a value

var referrer = $document.referrer;

A value is required

$document.referrer 

in a variable.

+4
source share
1 answer

$ document is actually the result of a jqLite / jQuery soi request, the property does not exist. If you want to get a referrer, you can:

a) Direct access to the DOM document:

var referrer = document.referrer; 

This is not recommended as you will end up with problems writing unit tests.

b) Object reference inside jqLite / jQuery query result:

var referrer = $document[0].referrer;

Personally, I also don’t like this approach, 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;

, , .

+3

Source: https://habr.com/ru/post/1608810/


All Articles