首页 > 解决方案 > 谷歌标签管理器自定义模板沙盒 Javascript 问题

问题描述

我已经使用谷歌标签管理器创建了一个自定义模板,但是我在让我的沙盒 javascript 工作时遇到了一些困难,我知道脚本是正确注入的,因为以下

log('Cotaylits: 脚本加载成功。');

输出到控制台。我只是无法调用我的函数。我也包含了 JS 代码。

自定义模板代码(沙盒 Javascript)

// Enter your template code here.
const log = require('logToConsole');
const injectScript = require('injectScript');
const copyFromWindow = require('copyFromWindow');
const callInWindow = require('callInWindow');
const callLater = require('callLater');
const setInWindow = require('setInWindow');

const key = "testing";
const value = "test2";
const url = 'https://api.deve/cotalytics/cotalytics.js';


// If the script loaded successfully, log a message and signal success
const onSuccess = () => {
  log('Cotaylitcs: Script loaded successfully.');


  const cotalytics = copyFromWindow('cotalytics');
  log(cotalytics);
  callInWindow('cotalytics.addEvent',"testing12" ,{key: value}, "{{DL - cottageCode}}");
  callInWindow('cotalytics.logEvents()');
  data.gtmOnSuccess();
};

// If the script fails to load, log a message and signal failure
const onFailure = () => {
  log('Cotaylitcs: Script load failed.');
  data.gtmOnFailure();
};

injectScript(url, onSuccess, onFailure, 'cotalytics');


我由 Sandboxed Js 注入的 Javascript 代码:


let Cotalytics = function(){
    this.init();
};

// Init
Cotalytics.prototype = 
{
    init: function () {

        var cotalytics = this;

        // Argument Assignment                                                                              
        //cotalytics.endpoint           =  'https://localhost:44301/api/events/',
        //cotalytics.async              =  true,
        //cotalytics.debug              = true,
        //cotalytics.events             = {}

        //creat cookie here

        return cotalytics;
    },
      // Add Interaction Object Triggered By Events to Records Array
    addEvent: function (eventType, data, cottageCode, brandid) {
        data = data || {};
        cottageCode = cottageCode || null;

        data.Browser = window.navigator.appVersion;

        var cotalytics  = this;

            // cotalytics Object
            cotalytics.events     = {
                timestamp       : new Date(),
                cottagecode     : cottageCode,
                type            : eventType,
                ipaddress       : "127.0.0.1",
                requesturl      : window.location.href,
                sessionid       : "1234567",
                brandid         : brandid,
                eventData  : Object.keys(data).map(function(key) { return {"key": key, "value": data[key]}})
            };


        // Log Interaction if Debugging

            //cotalytics.logEvents();
            //console.log("Session:\n", interactor.interaction);
            //var data =JSON.stringify(interactor)
           console.log("JSON:\n", JSON.stringify(cotalytics));


        return cotalytics;
    },
     // Gather Additional Data and Send Interaction(s) to Server
     logEvents: function () {

        var cotalytics  = this,
            // Initialize Cross Header Request
            xhr         = new XMLHttpRequest();

        // Post Session Data Serialized as JSON
        xhr.open('POST', 'https://localhost:44301/api/events/', true);

        xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
        var data = JSON.stringify(cotalytics.events);
        xhr.send(data);

        return cotalytics;
        }
};


window.cotalytics = new Cotalytics();



标签: javascriptgoogle-tag-manager

解决方案


好的,看起来您大部分时间都在那里,但有些事情不太正确。

  1. {key: value}在 addEvent 调用中使用。虽然值将用您的常量填充,但键不会。我想象这些将是动态变量,所以你为什么没有类似的东西:
const kvp= {};
const key = "yourKey";
const value = "yourValue";
kvp[key] = value;

这将使用您想要的键创建对象,而不仅仅是“键”。

  1. 这条线在这里行不通。您不能在自定义模板中使用容器变量。

callInWindow('cotalytics.addEvent',"testing12" ,{key: value}, "{{DL - cottageCode}}");

它看起来像一个 dataLayer 变量,那么为什么不使用 copyFromDataLayer API 并尝试一下呢?

const copyFromDataLayer = require('copyFromDataLayer');
const cottageCode = copyFromDataLayer('cottageCode');
  1. logEvents callInWindowcallInWindow('cotalytics.logEvents()');不需要括号,它只是callInWindow('cotalytics.logEvents');.

我得到的最终代码是:

const log = require('logToConsole');
const injectScript = require('injectScript');
const callInWindow = require('callInWindow');
const makeTableMap = require('makeTableMap');
const copyFromDataLayer = require('copyFromDataLayer');

const cottageCode = copyFromDataLayer('cottageCode');

//Create the Key Value Pair
const kvp = {};
const key = "testing";
const value = "test2";
kvp[key]=value;

const url = "https://api.deve/cotalytics/cotalytics.js";

// If the script loaded successfully, log a message and signal success
const onSuccess = () => {
  log('Cotaylitcs: Script loaded successfully.');
  callInWindow('cotalytics.addEvent',"testing12" ,kvp,cottageCode);
  callInWindow('cotalytics.logEvents');
  data.gtmOnSuccess();
};

// If the script fails to load, log a message and signal failure
const onFailure = () => {
  log('Cotaylitcs: Script load failed.');
  data.gtmOnFailure();
};

injectScript(url, onSuccess, onFailure, 'cotalytics');

希望对您有所帮助,如果您还有其他问题,请询问!


推荐阅读