自定义HTML标记:用于userType dataLayer push的JS编译错误

时间:2017-06-21 17:39:04

标签: google-analytics javascript google-tag-manager

如果你愿意的话,我一直试图让现有的(和工作标签)更加高效/优雅。

所以情况是,我们有一种通过GTM Custom HTML标签将userType推送到dataLayer的方法。但是,在尝试发布标记时,我遇到了编译错误。

这是标签:

<script>
(function() {
var ipaddress;;
var type = 'external';
try {
  jQuery.getJSON('https://ipinfo.io', function(data) {
    ipaddress = data.ip;
    var internal = [
      "IP address",
      "IP address",
      "IP address",
      "IP address",
      "IP address",
      "IP address",
      "IP address",
      "IP address",
      "IP address",
      "IP address",
      "IP address",
      "IP address",
      "IP address",
      "IP address"
    ];
    var userType = internal.indexOf(ipaddress) == -1 ? ‘external’ : ‘internal’;
    }
    if (ipaddress) {
      window.dataLayer.push({
        event: 'ipResolved',
        ipaddress: ipaddress,
        userType: userType
      });
    }
  });
} catch(e) {
  window.dataLayer.push({
    event: 'ipResolved',
    ipaddress: 'N/A',
    iplocation: 'N/A'
  });
 }
})();
</script>

任何人都可以了解我出错的地方吗?我觉得我太接近了,所以我看不到明显的。

1 个答案:

答案 0 :(得分:0)

你的JS有一些小错误:

  • 错误的引号。它是而不是'
  • 一个不必要的}

。工作版本在这里:

(function() {
var ipaddress;
var type = 'external';
try {
  jQuery.getJSON('https://ipinfo.io', function(data) {
    ipaddress = data.ip;
    var internal = [
      "IP address",
      "IP address",
      "IP address",
      "IP address",
      "IP address",
      "IP address",
      "IP address",
      "IP address",
      "IP address",
      "IP address",
      "IP address",
      "IP address",
      "IP address",
      "IP address"
    ];
    var userType = internal.indexOf(ipaddress) == -1 ? 'external' : 'internal';

    if (ipaddress) {
      window.dataLayer.push({
        event: 'ipResolved',
        ipaddress: ipaddress,
        userType: userType
      });
    }
  });
} catch(e) {
  window.dataLayer.push({
    event: 'ipResolved',
    ipaddress: 'N/A',
    iplocation: 'N/A'
  });
 }
})();