UNPKG

vue-tag-manager

Version:

Easy to use Google Tag Manager implementation for Vue

165 lines (153 loc) 6.52 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (factory((global.VueTagManager = {}))); }(this, (function (exports) { 'use strict'; /*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ var __assign = function() { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; /** * Global Tag Manager instance */ var TagManager = /** @class */ (function () { function TagManager(options) { this.options = { gtmId: undefined, queryParams: {}, dataLayerName: "dataLayer", dataLayer: undefined, scriptUrl: "//www.googletagmanager.com/gtm.js" }; this.options = __assign({}, this.options, options); if (!this.options.gtmId) { throw "No GTM id provided"; } } /** * Returns the URL and query params to get the tag manager script */ TagManager.prototype.getScriptUrl = function () { var id = this.options.gtmId; var url = this.options.scriptUrl; var queryParams = __assign({ id: id, l: this.options.dataLayerName }, this.options.queryParams); var queryString = Object.keys(queryParams) .filter(function (key) { return queryParams[key] !== null && queryParams[key] !== undefined; }) .map(function (key) { return encodeURIComponent(key) + "=" + encodeURIComponent(queryParams[key]); }) .join("&"); return url + "?" + queryString; }; /** * Returns the script to initialize the data layer */ TagManager.prototype.getDataLayerScriptContent = function () { var dataLayerName = this.options.dataLayerName; var initialValues = this.options.dataLayer; var scriptArray = []; // Initialize data layer scriptArray.push("window['" + dataLayerName + "'] = window['" + dataLayerName + "'] || [];"); if (initialValues) { scriptArray.push("window['" + dataLayerName + "'].push(" + JSON.stringify(initialValues) + ");"); } scriptArray.push("window['" + dataLayerName + "'].push({ event: 'gtm.js', 'gtm.start': new Date().getTime() });"); return scriptArray.join("\n"); }; /** * Push an event to the data layer * @param event event object */ TagManager.prototype.push = function (event) { if (!(event instanceof Object) || event instanceof Array) throw "Pushed event is not an object."; var dataLayer = this.options.dataLayerName; window[dataLayer].push(event); }; return TagManager; }()); /** * Creates an empty script tag */ var createScriptTag = function () { var scriptTag = document.createElement("script"); return scriptTag; }; /** * Returns a script tag with a src url * @param src src url of the script * @param isAsync script load async */ var getScriptTagWithSrc = function (src, isAsync) { if (isAsync === void 0) { isAsync = false; } if (!src) throw "No src passed."; var scriptTag = createScriptTag(); scriptTag.src = src; scriptTag.async = isAsync; return scriptTag; }; /** * Returns a script tag with provided script injected * @param script content to be injected into a script tag */ var getScriptTagWithContent = function (script) { if (!script) throw "No script content passed."; var scriptTag = createScriptTag(); scriptTag.innerHTML = script; return scriptTag; }; /** * Injects the provided script tag into the head * @param scriptTag script tag to inject into head */ var injectScriptTagIntoHead = function (scriptTag) { if (!scriptTag) throw "No script tag passed."; window.document.head.appendChild(scriptTag); }; var warn = function () { var messages = []; for (var _i = 0; _i < arguments.length; _i++) { messages[_i] = arguments[_i]; } console.warn.apply(console, ["[vue-tag-manager]:"].concat(messages)); }; window.vgtmInstalled = false; var initialize = function (options) { if (window.vgtmInstalled) return; try { var tagManager = new TagManager(options); injectScriptTagIntoHead(getScriptTagWithContent(tagManager.getDataLayerScriptContent())); injectScriptTagIntoHead(getScriptTagWithSrc(tagManager.getScriptUrl(), true)); var variableName = options.TagManagerVariableName || "TagManager"; window[variableName] = tagManager; window.vgtmInstalled = true; } catch (error) { warn(error); } }; exports.initialize = initialize; Object.defineProperty(exports, '__esModule', { value: true }); })));