LoginSignup
0
0

More than 1 year has passed since last update.

GoogleAppsScriptでGoogle タグマネージャの操作

Posted at

概要

  • Google タグマネージャに登録されているタグを一度に停止する必要があったので作成したスクリプト
  • GoogleAppsScriptを使ったのは、Google シートでリストの管理ができるからという理由から

参考

手順

事前情報

GTMのアカウントIDとコンテナIDの取得方法

  • GTM設定画面でコンテナを開いてURLから取得
    • 例:tagmanager.google.com/#/admin/accounts/1234567890/containers/98765432

タグID

  • GTM管理画面のタグ一覧で、当該タグにマウスを重ねて表示されるURLから取得できる
  • 私はエクスポートしたコンテナのJSONファイルから一覧を作成している

スプレッドシートの記述内容

次の内容でtags_to_pauseというシートを作成

tagId name pause
1 タグ名1 TRUE
2 タグ名2 TRUE
3 タグ名3 TRUE
  • 停止したいタグのpause列にTRUEとセット(FALSEとした場合は無視される)

GASスクリプトの追加

GASプロジェクトを開いて、次のコードをペースト

main.js
const SHEET_TAGS_TO_PAUSE = "tags_to_pause";
const GTM_ACCOUNT_ID = "XXXX";
const GTM_CONTAINER_ID = "XXXXX";

function pauseTagsOnList() {

  // 設定情報の読込
  var records = parseTableInSheet_(SHEET_TAGS_TO_PAUSE);

  // 最新のWorkspaceを取得
  var workspace_id = getWorkspaceId_(GTM_ACCOUNT_ID, GTM_CONTAINER_ID);
  if (!workspace_id) return;

  // タグの一覧を取得
  var active_tag_ids = getActiveTagIds_(GTM_ACCOUNT_ID, GTM_CONTAINER_ID, workspace_id);
  if (!active_tag_ids) return;

  // 停止する対象
  records.forEach(tag => {

    if (tag.pause !== true) return;
    if (typeof active_tag_ids[tag.tagId] === 'undefined') return;

    // 提示の実行
    console.log(`Pausing Tag: [${tag.tagId}] ${tag.name}`);

    // 対象のタグ
    var path = `accounts/${GTM_ACCOUNT_ID}/containers/${GTM_CONTAINER_ID}/workspaces/${workspace_id}/tags/${tag.tagId}`;

    // タグの情報を取得
    try {
      var target = TagManager.Accounts.Containers.Workspaces.Tags.get(path);
    } catch (e) {
      console.error(`Failed to get tag info of ${path}: ${e}`);
    }

    // タグの停止
    // (停止でなく削除したければ`update`の代わりに`delete`を利用)
    try {
      var result = TagManager.Accounts.Containers.Workspaces.Tags.update({
        name: target.name,
        type: target.type,
        parameter: target.parameter,
        paused: true
      },path);
      if (result.error) {
        throw (error.message);
      }
    } catch (e) {
      console.error(`Failed Pausing Tag [${tag.tagId}]: ${e.message}`);
    }
  })
}

/*
 * getCurrentTagIds(account_id, container_id)
 */

function getActiveTagIds_(account_id, container_id, workspace_id) {

  // 現在のタグ一覧を取得
  var tag_ids = {};
  try {
  var path = `accounts/${account_id}/containers/${container_id}/workspaces/${workspace_id}`
    var tags = TagManager.Accounts.Containers.Workspaces.Tags.list(path);
    tags.tag.forEach(i => {
      if ( i.paused ) return;
      tag_ids[i.tagId] = i.name + "a" + i.paused;
    });
    return tag_ids;
  } catch (e) {
    console.error(`Failed to get list from GTM API ${path}: ${e}`)
  }

}

/*
 * getWorkspaceId_(account_id, container_id)
 */

function getWorkspaceId_(account_id, container_id){

  // Workspaceを取得
  try{
    var path = `accounts/${account_id}/containers/${container_id}`;
    var workspaces = TagManager.Accounts.Containers.Workspaces.list(path);
    var workspace_id = workspaces.workspace[0].workspaceId;
    return workspace_id;
  }catch(e){
    console.error(`Failed to get workspace id: ${e}`)
  }

}

/*
 * parseTableInSheet_(sheet)
 */


function parseTableInSheet_(sheetname) {

  // シートオブジェクトから情報を取得
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = spreadsheet.getSheetByName(sheetname);
  var range = sheet.getRange(1, 1, sheet.getMaxRows(), sheet.getMaxColumns());
  var rows = range.getValues();
  var header = null;
  var records = [];
  rows.forEach(row => {
    if (!row[0]) return;
    if (!header) {
      header = row.filter(i => { return i ? true : false });
      return;
    }
    var record = {};
    header.forEach(field => {
      record[field] = row.shift();
    })
    records.push(record);
  })

  return records;

}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0