任何人都可以帮助改进这个复制/粘贴弗兰肯斯坦的javascript怪物吗?
我正在尝试从Cookie中检索特定数据,将其拼接在一起,然后按https://support.google.com/analytics/answer/3123666的用户ID发送到Google Analytics。
我所拥有的将会起作用(我认为),但可能完全没有效率,而且可能有很多冗余。
cookiename 的价值是:
"{\"number1\":123,\"number2\":456,\"otherthing\":null}"
我想将其设置为用户ID:
123.456
我遇到的挑战:
我最终得到了什么:
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function idmaker() {
var cookievalue = decodeURI(getCookie("cookiename"));
var tidiedcookievalue = cookievalue.replace(/\\/g, "").slice(1, -1);
var parsedcookie = JSON.parse(tidiedcookievalue);
var UID = parsedcookie.number1 + "." + parsedcookie.number2;
return UID;
}
function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
}(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-12345678-9', 'auto');
ga('set', 'userId', idmaker());
ga('send', 'pageview');
请摧毁我。