샌드박스 환경의 JavaScript는 Google 태그 관리자 맞춤 템플릿의 임의의 JavaScript 로직을 안전하게 실행하는 방법을 제공하는 JavaScript 언어의 단순화된 하위 집합입니다. 안전한 실행 환경을 제공하기 위해 JavaScript의 일부 기능이 제한되거나 삭제됩니다. 샌드박스 환경의 JavaScript는 ECMAScript 5.1을 기반으로 합니다. 화살표 함수 및 const/let 선언과 같은 일부 ECMAScript 6 기능을 사용할 수 있습니다.
전역 실행 환경
샌드박스 환경의 JavaScript는 일반 JavaScript와 같은 표준 전역 실행 환경에서 실행되지 않으므로 window 객체 및 속성을 사용할 수 없습니다. 여기에는 encodeURI 또는 setTimeout과 같이 전역 범위에 정의된 메서드, location 또는 document와 같은 전역 값, 로드된 스크립트로 정의된 전역 값이 포함됩니다. 이러한 값의 자리에서, 이 함수 대부분을 제공하는 샌드박스 환경의 모든 JavaScript에 전역 require 함수를 사용할 수 있습니다. copyFromWindow 유틸리티를 사용하여 창에서 값을 읽을 수 있습니다.
단순화된 유형 시스템
샌드박스 환경의 JavaScript는 null, undefined, string, number, boolean, array, object, function 유형을 지원합니다. 배열 및 객체는 리터럴 구문([] {})을 사용하여 생성되며, 표준 전역 실행 환경에 액세스할 수 없으므로 String() 및 Number()와 같은 전역 생성자는 사용할 수 없습니다. 샌드박스 환경의 JavaScript에는 new 키워드가 없으며 함수에서 this 키워드에 액세스할 수 없습니다.
일부 네이티브 유형 메서드도 삭제되었습니다. 지원되는 네이티브 유형 메서드의 전체 목록은 표준 라이브러리를 참고하세요.
맞춤 템플릿 코드 형식
맞춤 템플릿을 구현하기 위해 작성된 코드는 태그가 실행되거나 변수가 평가될 때마다 실행되는 함수의 본문을 나타냅니다. 이 함수에는 해당 태그 또는 변수 인스턴스의 UI에 구성된 모든 값이 포함된 단일 데이터 매개변수(data)가 있으며, 키는 맞춤 템플릿에 지정된 템플릿 매개변수의 이름으로 설정되어 있습니다.
[null,null,["최종 업데이트: 2024-04-17(UTC)"],[[["\u003cp\u003eSandboxed JavaScript in Google Tag Manager offers a secure environment to execute custom code with limited features for safety.\u003c/p\u003e\n"],["\u003cp\u003eIt utilizes a simplified type system and lacks access to the standard JavaScript global execution environment, relying on a \u003ccode\u003erequire\u003c/code\u003e function for functionalities like \u003ccode\u003eencodeURI\u003c/code\u003e or \u003ccode\u003esetTimeout\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003eCustom template code acts as a function executed upon tag firing or variable evaluation, receiving configured data through a \u003ccode\u003edata\u003c/code\u003e parameter.\u003c/p\u003e\n"],["\u003cp\u003eThe provided sample demonstrates building a beacon tag using \u003ccode\u003erequire\u003c/code\u003e for functionalities and accessing configuration data via \u003ccode\u003edata\u003c/code\u003e.\u003c/p\u003e\n"]]],["Sandboxed JavaScript, used in Google Tag Manager's custom templates, provides a safe execution environment with restricted features. It uses a simplified type system and lacks the standard `window` object, instead relying on a `require` function for globals. It supports basic types and literal array/object creation. Template code represents a function body with a `data` parameter containing UI-configured values. Code example uses functions `sendPixel`, `encodeUri`, `encodeUriComponent` for building a URL and appending cache buster parameter, then send the pixel with `sendPixel`.\n"],null,["# Sandboxed JavaScript is a simplified subset of the JavaScript language that\nprovides a safe way to execute arbitrary JavaScript logic from Google Tag\nManager's custom templates. To provide a safe execution environment, some\nfeatures of JavaScript are restricted or removed. Sandboxed JavaScript is based\non ECMAScript 5.1. Some ECMAScript 6 features such as arrow functions and\n`const`/`let` declarations are available.\n\nGlobal execution environment\n----------------------------\n\nSandboxed JavaScript is not executed in the standard global execution\nenvironment like normal JavaScript, so the `window` object and its properties\nare not available. This includes methods defined in the global scope like\n`encodeURI` or `setTimeout`, global values like `location` or `document`, and\nglobal values defined by loaded scripts. In place of these, a global `require`\nfunction is available to all sandboxed JavaScript that provides many of these\nfunctions. Values can be read from the window with the\n[`copyFromWindow`](/tag-platform/tag-manager/templates/api#copyfromwindow) utility.\n| **Note:** `copyFromWindow` creates a deep copy of the values, and it can be an expensive operation to pass those values into and out of the sandbox.\n\nSimplified type system\n----------------------\n\nSandboxed JavaScript supports the following types: `null`, `undefined`,\n`string`, `number`, `boolean`, `array`, `object`, and `function`. Arrays and\nobjects are created using the literal syntax ( `[] {}` ), and because there's no\naccess to the standard global execution environment, global constructors like\n`String()` and `Number()` aren't available. There is no `new` keyword in\nsandboxed JavaScript, and functions do not have access to the `this` keyword.\nSome native type methods have also been removed. See [standard library](/tag-platform/tag-manager/templates/standard-library) for an\nexhaustive list of supported native type methods.\n\nCustom template code format\n---------------------------\n\nThe code written to implement a custom template represents the body of a\nfunction that will be executed whenever your tag is fired or your variable is\nevaluated. This function has a single data parameter (`data`) that holds all the\nvalues configured in the UI for that tag or variable instance, with the keys set\nto the names of the template parameters specified in the custom template.\n\nSample beacon tag implementation\n--------------------------------\n\n const sendPixel = require('sendPixel');\n const encodeUri = require('encodeUri');\n const encodeUriComponent = require('encodeUriComponent');\n\n let url = encodeUri(data['url']);\n\n if (data['useCacheBuster']) {\n const encode = require('encodeUriComponent');\n const cacheBusterQueryParam = data['cacheBusterQueryParam'] || 'gtmcb';\n const last = url.charAt(url.length - 1);\n let delimiter = '&';\n if (url.indexOf('?') \u003c 0) {\n delimiter = '?';\n } else if (last == '?' || last == '&') {\n delimiter = '';\n }\n url += delimiter +\n encodeUriComponent(cacheBusterQueryParam) + '=' + encodeUriComponent(data['randomNumber']);\n }\n sendPixel(url, data['gtmOnSuccess'], data['gtmOnFailure']);"]]