Override referrer Google Analytics with JS or JQ

孤者浪人 提交于 2021-02-11 01:42:51

问题


I am trying to override the referrer of Google Analytics without touching the main Google analytics script or config. The problem is that it is not working. And Google Analytics from what I saw takes the document.referer variable, based on my script it does change the document.referer variable but still not working.

<script>
    $(document).ready(function(e) { 
        function change_referrer() {
            Object.defineProperty(document, "referrer", {get : function(){
                var referers = [
                    'twitter.com',
                    'google.com',
                    'facebook.com',
                    'instagram.com'
                ];
                var the_referer = sessionStorage.getItem("the_referer");
                if(!the_referer) {
                    var the_referer = referers.randomElement();
                    sessionStorage.setItem("the_referer", the_referer);
                }
                return the_referer;
            }});
            //ga('set', 'referrer', 'http://'+the_referer);
            console.log(document.referrer);
        }
        change_referrer();
    });
</script>
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXX-1"></script>
<script>
    window.dataLayer = window.dataLayer || [];
    function gtag(){
        dataLayer.push(arguments);
    }
    gtag('js', new Date());
    gtag('config', 'UA-XXXXXXXX-1');
</script>

回答1:


Just came across this issue when trying to set iframe's parent URL as a referrer. I ended up doing this and it works:

gtag('set', {
    referrer: "https://your-referrer-url.com"
})


来源:https://stackoverflow.com/questions/57400176/override-referrer-google-analytics-with-js-or-jq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!