שירות TagManager

שירות Google Tag Manager מספק למשתמש מורשה גישה לנתונים של Tag Manager API. השירות הזה מאפשר למשתמשי Tag Manager לנהל חשבונות, מאגרי תגים, סביבות, גרסאות, סביבות עבודה, תיקיות, משתנים, טריגרים, תגים והרשאות משתמש ב-Tag Manager.

חומרי עזר

מידע מפורט על השירות הזה זמין במאמרי העזרה בנושא Tag Manager API V2.

בדומה לכל השירותים המתקדמים ב-Apps Script, השירות Tag Manager משתמש באותם אובייקטים, שיטות ופרמטרים כמו ה-API הציבורי. מידע נוסף זמין במאמר איך נקבעות חתימות של שיטות.

כדי לדווח על בעיות ולקבל תמיכה נוספת, אפשר לעיין במרכז העזרה של Google Tag Manager.

קוד לדוגמה

בדוגמת הקוד הבאה מוצגות כמה תכונות של שירות Tag Manager.

יצירת גרסה של מאגר תגים עם משתנה, טריגר ותג.

בדוגמת הקוד שבהמשך נעשה שימוש ב-Tag Manager API V2 כדי ליצור מאגר עם שם שכולל חותמת זמן עם התאריך הנוכחי, כדי להגדיל את הסיכוי שהשם יהיה ייחודי. לאחר מכן, הדוגמה יוצרת מרחב עבודה עם משתנה של ערך אקראי וטריגר שמופעל בכל צפייה בדף. לאחר מכן, בדוגמה נעשה שימוש בטריגר כדי ליצור תג פיקסל שרירותי שמפעיל פיקסל אל //example.com עם תוסף למניעת אחסון במטמון שמצורף לסוף כתובת ה-URL. לבסוף, הדוגמה יוצרת גרסה של מאגר התגים עם הישויות שלמעלה, מתעדת את הגרסה ומחזירה אותה לשימוש מאוחר יותר.

advanced/tagManager.gs
/**
 * Creates a container version for a particular account
 * with the input accountPath.
 * @param {string} accountPath The account path.
 * @return {string} The tag manager container version.
 */
function createContainerVersion(accountPath) {
  const date = new Date();
  // Creates a container in the account, using the current timestamp to make
  // sure the container is unique.
  try {
    const container = TagManager.Accounts.Containers.create(
        {
          'name': 'appscript tagmanager container ' + date.getTime(),
          'usageContext': ['WEB']
        },
        accountPath);
    const containerPath = container.path;
    // Creates a workspace in the container to track entity changes.
    const workspace = TagManager.Accounts.Containers.Workspaces.create(
        {'name': 'appscript workspace', 'description': 'appscript workspace'},
        containerPath);
    const workspacePath = workspace.path;
    // Creates a random value variable.
    const variable = TagManager.Accounts.Containers.Workspaces.Variables.create(
        {'name': 'apps script variable', 'type': 'r'},
        workspacePath);
    // Creates a trigger that fires on any page view.
    const trigger = TagManager.Accounts.Containers.Workspaces.Triggers.create(
        {'name': 'apps script trigger', 'type': 'PAGEVIEW'},
        workspacePath);
    // Creates a arbitary pixel that fires the tag on all page views.
    const tag = TagManager.Accounts.Containers.Workspaces.Tags.create(
        {
          'name': 'apps script tag',
          'type': 'img',
          'liveOnly': false,
          'parameter': [
            {'type': 'boolean', 'key': 'useCacheBuster', 'value': 'true'}, {
              'type': 'template',
              'key': 'cacheBusterQueryParam',
              'value': 'gtmcb'
            },
            {'type': 'template', 'key': 'url', 'value': '//example.com'}
          ],
          'firingTriggerId': [trigger.triggerId]
        },
        workspacePath);
    // Creates a container version with the variabe, trigger, and tag.
    const version = TagManager.Accounts.Containers.Workspaces
        .create_version(
            {'name': 'apps script version'}, workspacePath)
        .containerVersion;
    console.log(version);
    return version;
  } catch (e) {
    // TODO (Developer) - Handle exception
    console.log('Failed with error: %s', e.error);
  }
}

מפרסמים גרסה של מאגר התגים ומציגים תצוגה מקדימה מהירה של טיוטת מאגר התגים הנוכחית.

בדוגמת הקוד שבהמשך נעשה שימוש ב-Tag Manager API V2 כדי לאשר גרסה של מאגר תגים שאולי נוצרה בדוגמה שלמעלה, ולשלוף את מזהי החשבון, מאגר התגים והגרסה מהגרסה. בדוגמה נעשה שימוש במזהים האלה כדי לפרסם גרסה של מאגר באופן פעיל לכל העולם. לבסוף, הדוגמה יוצרת תצוגה מקדימה מהירה של סביבת עבודה חדשה ומתעדת את התצוגה המקדימה המהירה.

advanced/tagManager.gs
/**
 * Retrieves the container path from a container version path.
 * @param  {string} versionPath The version path.
 * @return {string}             The container path.
 */
function grabContainerPath(versionPath) {
  const pathParts = versionPath.split('/');
  return pathParts.slice(0, 4).join('/');
}

/**
 * Publishes a container version publically to the world and creates a quick
 * preview of the current container draft.
 * @param {object} version The container version.
 */
function publishVersionAndQuickPreviewDraft(version) {
  try {
    const containerPath = grabContainerPath(version.path);
    // Publish the input container version.
    TagManager.Accounts.Containers.Versions.publish(version.path);
    const workspace = TagManager.Accounts.Containers.Workspaces.create(
        {'name': 'appscript workspace', 'description': 'appscript workspace'},
        containerPath);
    const workspaceId = workspace.path;
    // Quick previews the current container draft.
    const quickPreview = TagManager.Accounts.Containers.Workspaces
        .quick_preview(workspace.path);
    console.log(quickPreview);
  } catch (e) {
    // TODO (Developer) - Handle exceptions
    console.log('Failed with error: $s', e.error);
  }
}

יוצר מחדש סביבת משתמש ומעניק לה הרשאה.

בדוגמת הקוד שבהמשך נעשה שימוש ב-Tag Manager API V2 כדי לאשר גרסת מאגר תגים ולחלץ את מזהי החשבון, מאגר התגים והגרסה. בדוגמה נעשה שימוש במזהים האלה כדי ליצור סביבת משתמש שמפנה לגרסת מאגר הקלט ומתעדת את סביבת המשתמש. הדוגמה מסתיימת ברישום של סביבת משתמש שקיבל הרשאה מחדש.

advanced/tagManager.gs
/**
 * Retrieves the container path from a container version path.
 * @param  {string} versionPath The version path.
 * @return {string}             The container path.
 */
function grabContainerPath(versionPath) {
  const pathParts = versionPath.split('/');
  return pathParts.slice(0, 4).join('/');
}

/**
 * Creates and reauthorizes a user environment in a container that points
 * to a container version passed in as an argument.
 * @param {object} version The container version object.
 */
function createAndReauthorizeUserEnvironment(version) {
  try {
    // Creates a container version.
    const containerPath = grabContainerPath(version.path);
    // Creates a user environment that points to a container version.
    const environment = TagManager.Accounts.Containers.Environments.create(
        {
          'name': 'test_environment',
          'type': 'user',
          'containerVersionId': version.containerVersionId
        },
        containerPath);
    console.log('Original user environment: ' + environment);
    // Reauthorizes the user environment that points to a container version.
    TagManager.Accounts.Containers.Environments.reauthorize(
        {}, environment.path);
    console.log('Reauthorized user environment: ' + environment);
  } catch (e) {
    // TODO (Developer) - Handle exceptions
    console.log('Failed with error: $s', e.error);
  }
}

יוצר יומן רישום של כל האימיילים וההרשאות לגישה למאגרים בחשבון.

בדוגמת הקוד שבהמשך נעשה שימוש ב-Tag Manager API V2 כדי למצוא רשימה של כל ההרשאות בחשבון Tag Manager. לאחר מכן, הדוגמה רושמת ביומן את כתובת האימייל של המשתמש, את מזהה מאגר התגים ואת סוגי הרשאות הגישה למאגר התגים לכל רשומה.

advanced/tagManager.gs
/**
 * Logs all emails and container access permission within an account.
 * @param {string} accountPath The account path.
 */
function logAllAccountUserPermissionsWithContainerAccess(accountPath) {
  try {
    const userPermissions =
      TagManager.Accounts.User_permissions.list(accountPath).userPermission;
    for (let i = 0; i < userPermissions.length; i++) {
      const userPermission = userPermissions[i];
      if ('emailAddress' in userPermission) {
        const containerAccesses = userPermission.containerAccess;
        for (let j = 0; j < containerAccesses.length; j++) {
          const containerAccess = containerAccesses[j];
          console.log(
              'emailAddress:' + userPermission.emailAddress +
            ' containerId:' + containerAccess.containerId +
            ' containerAccess:' + containerAccess.permission);
        }
      }
    }
  } catch (e) {
    // TODO (Developer) - Handle exceptions
    console.log('Failed with error: $s', e.error);
  }
}