JavaScript 跨域Google Analytics广告系列转置

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaScript 跨域Google Analytics广告系列转置相关的知识,希望对你有一定的参考价值。

/**
 * URL link updater for cross-site UTM code transposing
 * 
 * Update the validURLPattern variable regular expression to match your desired pattern
 * that indicates link HREF values that go to the second-site.
 */
try {
    // URL pattern regular expression, change this to match your call to action links
    var validURLPattern = new RegExp("my-conversion-point-domain\.com");
    // The search string
    var queryStr = document.location.search;
    
    // Only update if we have UTM parameters
    if(queryStr.match(/utm_campaign|utm_source|utm_medium/)){
        // Build object of UTM parameters
        var utm = {
            campaign: queryStr.match(/utm_campaign/) ? queryStr.match(/utm_campaign\=([^&]*)/)[1] : "",
            source: queryStr.match(/utm_source/) ? queryStr.match(/utm_source\=([^&]*)/)[1] : "",
            medium: queryStr.match(/utm_medium/) ? queryStr.match(/utm_medium\=([^&]*)/)[1] : ""
        };
        
        // Loop through all A tags and update
        $('a').each(function(){
            // Only update if HREF matches the URL pattern
            if(this.href.match(validURLPattern)){
                // Determine starting separator
                var sep = this.href.indexOf("?") == -1 ? "?" : "&";
                
                // Loop through UTM parameters to update
                for(var k in utm){
                    // Check if URL already contains this UTM parameter
                    if(this.href.indexOf("utm_" + k) != -1){
                        var regexp = new RegExp("utm_" + k + "=([^&]*)");
                        this.href = this.href.replace(regexp, "utm_" + k + "=" + utm[k]);
                    }
                    // Append if not
                    else {
                        this.href += sep + "utm_" + k + "=" + utm[k];
                        // Change separator now since we're appending to a now existing query string
                        sep = "&";
                    }
                }
            }
        });
    }
} catch(e) {}

以上是关于JavaScript 跨域Google Analytics广告系列转置的主要内容,如果未能解决你的问题,请参考以下文章

检查跨域 url 是不是使用 javascript 给出 404

如何使用 Javascript 从 iframe 实现跨域 URL 访问?

如何向 Google Site Search XML API 发出跨域浏览器请求?

如何读取跨域图像附带的 cookie 的值?

使用Access-Control-Allow-Origin解决跨域

使用Access-Control-Allow-Origin解决跨域