Google Publisher Tag Migrate To Setconfig

google/skills/skills/ads/google-publisher-tag-migrate-to-setconfig

作者 google35474caa2b668a8b6900fedb2049e613955efe56無授權條款25K 個星標收錄於 2026年12月1日更新於 2026年12月1日儲存庫今天更新

Migrates web publisher JavaScript and TypeScript code from deprecated Google Publisher Tag (GPT) setter and getter methods on googletag.pubads() and googletag.Slot to setConfig() and getConfig(). Use when auditing, updating, or refactoring GPT or googletag code in web scripts, ad wrappers, or frontend components to replace deprecated configuration APIs (such as setTargeting, clearTargeting, updateTargetingFromMap, collapseEmptyDivs, setCollapseEmptyDiv, enableSingleRequest, disableInitialLoad, enableLazyLoad, setSafeFrameConfig, setForceSafeFrame, setCategoryExclusion, clearCategoryExclusions, setVideoContent, setLocation, setCookieOptions, setRequestNonPersonalizedAds, or getTargeting). Don't use for non-GPT ad server integrations.

精選僅含說明軟體開發
AI 產生的概覽

將 Google Publisher Tag 程式碼中已棄用的 pubads 與 Slot 設定器及取得器遷移至 setConfig 和 getConfig。

功能
提供參考工作流程與對照表,用於把 googletag.pubads() 和 googletag.Slot 上已棄用的 Google Publisher Tag(GPT)方法替換為 setConfig() 和 getConfig()。內容涵蓋頁面層級與廣告版位層級的設定器與取得器、集合的合併與清除、SafeFrame、影片廣告、延遲載入、動態指定目標、隱私設定以及已移除的 API。也列出必須保持不變的 API 與驗證步驟,例如 node --check 以及查看 GPT 主控台警告。
適用情境
適用於稽核、更新或重構網頁指令碼、廣告封裝或前端元件中的 GPT 或 googletag 程式碼,以替換已棄用的設定 API。不適用於非 GPT 的廣告伺服器整合。
執行需求
僅為說明文件,不附帶指令碼。TypeScript 專案應更新 @types/google-publisher-tag 以及本地的 googletag 或 Slot 介面;驗證可使用專案現有檢查、node --check,或載入 gpt.js 的瀏覽器/E2E 測試。

AI 概覽如何產生和驗證

Migrate Google Publisher Tag configuration to setConfig and getConfig

Replace deprecated Google Publisher Tag (GPT) setters and getters on googletag.pubads() and googletag.Slot with setConfig() and getConfig() without changing ad request behavior. This skill is the complete reference for GPT setConfig and getConfig mappings and validation rules, so you don't need to search the web.

Workflow

Batch edits per file and validate once at the end.

  • 1. Update TypeScript types in TypeScript projects. Update @types/google-publisher-tag to the latest release in package.json, and update local googletag or Slot interfaces to declare setConfig and getConfig. Run a package-manager install only if node_modules already exists, because sandboxed environments are often offline.
  • 2. Inventory GPT calls in a single pass. Read named files directly. For a directory, search for googletag to find entry points, then follow where Slot and PubAdsService objects are passed. Sort what you find into deprecated setters and getters, existing setConfig calls whose keys must be preserved, privacy and removed APIs, and APIs to keep unchanged.
  • 3. Migrate page-level setters. Use the page-level setters and privacy and removed APIs tables with the migration rules.
  • 4. Migrate slot-level setters. Use the slot-level setters table with the migration rules.
  • 5. Migrate getters and feature checks. Use the page-level getters and slot-level getters tables. Remove legacy fallback branches and change feature checks to test for getConfig.
  • 6. Validate.
    • If node_modules exists, run the project's existing checks. For standalone files without a test suite, run node --check {file_path} and review your diff instead of writing ad-hoc test scripts.
    • When browser or E2E tests run live gpt.js, read the console output. Invalid setConfig and getConfig properties don't throw. GPT logs a warning and ignores them.
    • If a check fails or logs GPT console warnings, fix the code and run it again.

Migration rules

Page settings: one call on googletag

Page-level setConfig and getConfig exist only on googletag. PubAdsService has no setConfig, so googletag.pubads().setConfig() throws a TypeError, including through an alias such as const pubadsService = googletag.pubads().

  • Merge page settings from the same googletag.cmd.push callback or function into one googletag.setConfig() call before googletag.enableServices(), even when other calls such as defineSlot sit between them.
  • Don't merge across separate <script> tags, or across cmd.push blocks split by async header-bidding calls. They run at different times.
  • Replace detached method references too, such as const clear = pubads.clearTargeting or labels.forEach(pubads.setCategoryExclusion).
// Before
googletag.cmd.push(() => {
  const pubads = googletag.pubads();
  pubads.enableSingleRequest();
  googletag.defineSlot('/1234/banner', [728, 90], 'banner')
      ?.addService(pubads);
  pubads.collapseEmptyDivs();
  ['politics', 'gambling'].forEach(pubads.setCategoryExclusion);
  googletag.enableServices();
});

// After
googletag.cmd.push(() => {
  googletag.setConfig({
    singleRequest: true,
    collapseDiv: 'ON_NO_FILL',
    categoryExclusion: ['politics', 'gambling'],
  });
  googletag.defineSlot('/1234/banner', [728, 90], 'banner')
      ?.addService(googletag.pubads());
  googletag.enableServices();
});

Merging and clearing collections

Separate setConfig calls update collection settings instead of replacing them:

SettingSeparate callsClear one entryClear everything
targeting, adsenseAttributesMerge keys{ [key]: null }null
categoryExclusionAppend unique non-empty labels; [] is a no-opNot supportednull
  • Merge adjacent setCategoryExclusion calls or loops into one array.
  • When legacy code clears and then re-adds, clear with null in its own call first. Otherwise stale keys and labels survive. This applies to clearTargeting() followed by setTargeting() or updateTargetingFromMap(), and to clearCategoryExclusions() followed by setCategoryExclusion().
// Before
slot.clearTargeting();
slot.updateTargetingFromMap({ pos: 'top', section: 'news' });
slot.clearCategoryExclusions();
labels.forEach((label) => slot.setCategoryExclusion(label));

// After
slot.setConfig({ targeting: null });
slot.setConfig({ targeting: { pos: 'top', section: 'news' } });
slot.setConfig({ categoryExclusion: null });
if (labels.length > 0) {
  slot.setConfig({ categoryExclusion: labels });
}

SafeFrame and video ads

Merge related legacy calls on the same page or slot into one sub-object.

  • setForceSafeFrame() and setSafeFrameConfig() become one safeFrame object. Drop useUniqueDomain, which GPT ignores. Drop sandbox: false, because sandbox accepts only true or null.
  • enableVideoAds() and setVideoContent() become one videoAds object. Always include enableVideoAds: true, even for a standalone setVideoContent() call, because VideoAdsConfig requires it.
// Before
pubads.setForceSafeFrame(true);
pubads.setSafeFrameConfig({
  allowOverlayExpansion: false,
  useUniqueDomain: true,
  sandbox: false,
});
pubads.setVideoContent('content-id', 'cms-id');

// After
googletag.setConfig({
  safeFrame: { forceSafeFrame: true, allowOverlayExpansion: false },
  videoAds: {
    enableVideoAds: true,
    videoContentId: 'content-id',
    videoCmsId: 'cms-id',
  },
});

Collapsing empty divs

The legacy boolean means different things at page and slot level:

  • Page-level collapseEmptyDivs(false) still collapses on no fill, so it maps to 'ON_NO_FILL', never 'DISABLED'.
  • Slot-level setCollapseEmptyDiv(false) turns collapsing off, so it maps to 'DISABLED'.

The setter tables list every form. When a slot call is conditional, keep the condition and don't add an else branch that sets 'DISABLED'. The slot then inherits the page setting:

// Before
if (collapseBeforeFetch) slot.setCollapseEmptyDiv(true, true);

// After: no 'DISABLED' fallback branch
if (collapseBeforeFetch) slot.setConfig({ collapseDiv: 'BEFORE_FETCH' });

Lazy loading

setConfig rejects top-level properties set to undefined, and legacy lazy-load configs used -1 to mean "unset".

  • In wrappers where config may be undefined, default it to {}.
  • In wrappers where config is null, keep it null to clear the lazy-load setting.
  • Replace -1 with null in fetchMarginPercent, renderMarginPercent, and mobileScaling directly at call sites instead of adding a runtime helper.
// Before
googletag.pubads().enableLazyLoad({
  fetchMarginPercent: 300,
  renderMarginPercent: -1,
});
googletag.pubads().enableLazyLoad(config);

// After
googletag.setConfig({
  lazyLoad: {
    fetchMarginPercent: 300,
    renderMarginPercent: null,
  },
});
googletag.setConfig({ lazyLoad: config === undefined ? {} : config });

Dynamic targeting

setConfig validates targeting as Record<string, string | string[] | null> | null. It rejects empty or whitespace keys, undefined, numbers, booleans, and nested arrays.

null also changes meaning. Legacy setTargeting(key, null) was ignored, but { [key]: null } deletes the key, and String(null) sends 'null'.

When slot.updateTargetingFromMap(map) receives a map that already holds valid string, string[], or null values, pass it straight to slot.setConfig({ targeting: map }). Don't wrap it in a sanitizer. Maps that the caller builds and controls fit this case, such as header-bidding targeting maps and { [key]: null } maps that reset keys on purpose.

// Before
slot.updateTargetingFromMap(bidTargeting);
slot.updateTargetingFromMap({ pos: null, section: null });

// After
slot.setConfig({ targeting: bidTargeting });
slot.setConfig({ targeting: { pos: null, section: null } });

Sanitize only when the source can hold numbers, booleans, undefined, or nested arrays. That usually means setTargeting() calls with variable keys or values, including loops over Object.entries or Object.keys. Build a clean object instead of passing the source through:

// Before
for (const [key, value] of Object.entries(params)) {
  googletag.pubads().setTargeting(key, value);
}

// After
const targeting: Record<string, string | string[]> = {};
for (const [key, value] of Object.entries(params)) {
  if (!key.trim() || value == null) continue; // Skip, don't delete.
  if (Array.isArray(value)) {
    const values = value.flat(Infinity).filter((v) => v != null).map(String);
    if (values.length > 0) targeting[key] = values;
  } else {
    targeting[key] = String(value);
  }
}
if (Object.keys(targeting).length > 0) {
  googletag.setConfig({ targeting });
}

To clean an untyped updateTargetingFromMap map, use the same loop, but copy explicit null values through unchanged instead of skipping them. That way, intentional resets still delete their keys.

Reading settings with getConfig

  • googletag.getConfig() supports adsenseAttributes, disableInitialLoad, and targeting. slot.getConfig() supports adsenseAttributes, categoryExclusion, and targeting. Every other setting is write-only.
  • getConfig() returns a deeply frozen object keyed by setting name, never a flat map, so don't mutate it. getConfig('targeting') returns { targeting: { ... } }, which replaces loops over getTargetingKeys() and getTargeting(key).
  • Legacy getTargeting(key) always returned string[], or [] when unset. getConfig('targeting').targeting?.[key] is typed as string | string[] | null | undefined, so normalize it before calling array methods such as .includes(), .map(), or .length:
function toArray(value: string | string[] | null | undefined): string[] {
  if (Array.isArray(value)) return value;
  return value == null ? [] : [value];
}

const sections = toArray(slot.getConfig('targeting').targeting?.['section']);

Slot null checks and existing config

  • defineSlot() and defineOutOfPageSlot() return Slot | null. Check the slot before calling slot.setConfig().
  • Keep the keys of existing setConfig() calls when merging in new settings.
  • Rename deprecated adYield to threadYield if it appears in googletag.setConfig().

Page-level mapping

Use these tables to replace deprecated googletag.pubads() setters and getters with googletag.setConfig() and googletag.getConfig().

googletag.setConfig(config: googletag.config.PageSettingsConfig): void;
googletag.getConfig(keys: string | string[]): Readonly<
  Pick<
    googletag.config.PageSettingsConfig,
    'adsenseAttributes' | 'disableInitialLoad' | 'targeting'
  >
>;

Page-level setters

FeatureLegacy googletag.pubads() callReplacement
AdSense attributesset(key, value)googletag.setConfig({ adsenseAttributes: { [key]: value } })
Category exclusion (add)setCategoryExclusion(label)googletag.setConfig({ categoryExclusion: [label] })
Category exclusion (clear)clearCategoryExclusions()googletag.setConfig({ categoryExclusion: null })
CenteringsetCentering(isCentered)googletag.setConfig({ centering: isCentered })
Collapse empty divs (on no fill)collapseEmptyDivs() or collapseEmptyDivs(false)googletag.setConfig({ collapseDiv: 'ON_NO_FILL' })
Collapse empty divs (before fetch)collapseEmptyDivs(true)googletag.setConfig({ collapseDiv: 'BEFORE_FETCH' })
Initial loaddisableInitialLoad()googletag.setConfig({ disableInitialLoad: true })
Single Request ArchitectureenableSingleRequest()googletag.setConfig({ singleRequest: true })
Lazy loading (defaults)enableLazyLoad()googletag.setConfig({ lazyLoad: {} })
Lazy loading (custom)enableLazyLoad(config)googletag.setConfig({ lazyLoad: config === undefined ? {} : config })
Geographic locationsetLocation(address)googletag.setConfig({ location: address })
SafeFrame (force)setForceSafeFrame(force)googletag.setConfig({ safeFrame: { forceSafeFrame: force } })
SafeFrame (config)setSafeFrameConfig(config)googletag.setConfig({ safeFrame: config })
Targeting (set)setTargeting(key, value)googletag.setConfig({ targeting: { [key]: value } })
Targeting (clear one key)clearTargeting(key)googletag.setConfig({ targeting: { [key]: null } })
Targeting (clear all)clearTargeting()googletag.setConfig({ targeting: null })
Video ads (enable)enableVideoAds()googletag.setConfig({ videoAds: { enableVideoAds: true } })
Video ads (content)setVideoContent(contentId, cmsId)googletag.setConfig({ videoAds: { enableVideoAds: true, videoContentId: contentId, videoCmsId: cmsId } })

Page-level getters

toArray() is defined in Reading settings with getConfig.

Legacy googletag.pubads() callReplacement
get(key)googletag.getConfig('adsenseAttributes').adsenseAttributes?.[key] ?? null
getAttributeKeys()Object.keys(googletag.getConfig('adsenseAttributes').adsenseAttributes ?? {})
isInitialLoadDisabled()Boolean(googletag.getConfig('disableInitialLoad').disableInitialLoad)
getTargeting(key)toArray(googletag.getConfig('targeting').targeting?.[key])
getTargetingKeys()Object.keys(googletag.getConfig('targeting').targeting ?? {})

Slot-level mapping

Use these tables to replace deprecated googletag.Slot setters and getters with slot.setConfig() and slot.getConfig().

slot.setConfig(config: googletag.config.SlotSettingsConfig): googletag.Slot;
slot.getConfig(keys: string | string[]): Readonly<
  Pick<
    googletag.config.SlotSettingsConfig,
    'adsenseAttributes' | 'categoryExclusion' | 'targeting'
  >
>;

Slot-level setters

FeatureLegacy Slot callReplacement
AdSense attributesslot.set(key, value)slot.setConfig({ adsenseAttributes: { [key]: value } })
Category exclusion (add)slot.setCategoryExclusion(label)slot.setConfig({ categoryExclusion: [label] })
Category exclusion (clear)slot.clearCategoryExclusions()slot.setConfig({ categoryExclusion: null })
Click URL (non-SRA only)slot.setClickUrl(url)slot.setConfig({ clickUrl: url })
Collapse empty div (disabled)slot.setCollapseEmptyDiv(false) or slot.setCollapseEmptyDiv(false, true)slot.setConfig({ collapseDiv: 'DISABLED' })
Collapse empty div (on no fill)slot.setCollapseEmptyDiv(true) or slot.setCollapseEmptyDiv(true, false)slot.setConfig({ collapseDiv: 'ON_NO_FILL' })
Collapse empty div (before fetch)slot.setCollapseEmptyDiv(true, true)slot.setConfig({ collapseDiv: 'BEFORE_FETCH' })
SafeFrame (force)slot.setForceSafeFrame(force)slot.setConfig({ safeFrame: { forceSafeFrame: force } })
SafeFrame (config)slot.setSafeFrameConfig(config)slot.setConfig({ safeFrame: config })
Targeting (set)slot.setTargeting(key, value)slot.setConfig({ targeting: { [key]: value } })
Targeting (bulk map)slot.updateTargetingFromMap(map)slot.setConfig({ targeting: map })
Targeting (clear one key)slot.clearTargeting(key)slot.setConfig({ targeting: { [key]: null } })
Targeting (clear all)slot.clearTargeting()slot.setConfig({ targeting: null })

Slot-level getters

Legacy Slot callReplacement
slot.get(key)slot.getConfig('adsenseAttributes').adsenseAttributes?.[key] ?? null
slot.getAttributeKeys()Object.keys(slot.getConfig('adsenseAttributes').adsenseAttributes ?? {})
slot.getCategoryExclusions()slot.getConfig('categoryExclusion').categoryExclusion ?? []
slot.getTargeting(key)toArray(slot.getConfig('targeting').targeting?.[key])
slot.getTargetingKeys()Object.keys(slot.getConfig('targeting').targeting ?? {})
slot.getTargetingMap()slot.getConfig('targeting').targeting ?? {}

Privacy and removed APIs

Move legacy privacy setters to googletag.pubads().setPrivacySettings(), never to setConfig(). Delete calls that GPT has removed.

Legacy googletag.pubads() callReplacement
setRequestNonPersonalizedAds(0 | 1)googletag.pubads().setPrivacySettings({ nonPersonalizedAds: true | false })
setTagForChildDirectedTreatment(0 | 1)googletag.pubads().setPrivacySettings({ childDirectedTreatment: true | false })
clearTagForChildDirectedTreatment()googletag.pubads().setPrivacySettings({ childDirectedTreatment: null })
setTagForUnderAgeOfConsent(0 | 1 | -1)googletag.pubads().setPrivacySettings({ underAgeOfConsent: true | false | null })
setCookieOptions(options)Removed from GPT. Delete the call without setting cookieOptions in setConfig or setPrivacySettings.
setLocation(latitude, longitude, radius?)Removed from GPT. Delete the call. location accepts only an address string, such as '10001,US', or null.

Numeric flags map 1 to true, 0 to false, and -1 or a missing value to null. nonPersonalizedAds accepts only a boolean, so use Boolean(value). For wrappers that forward a numeric flag:

function toPrivacyFlag(value) {
  if (value === 1) return true;
  if (value === 0) return false;
  return null; // -1 or omitted
}

// Before: googletag.pubads().setTagForUnderAgeOfConsent(value);
googletag.pubads().setPrivacySettings({
  underAgeOfConsent: toPrivacyFlag(value),
});

APIs to keep unchanged

Migrate only the deprecated methods listed in the mapping tables above. Leave all other GPT and third-party calls unchanged, especially these common look-alikes:

  • googletag.pubads().setPrivacySettings(...): Keep on googletag.pubads(). googletag.setConfig({ privacyTreatments }) doesn't replace it.
  • googletag.pubads().setPublisherProvidedId(ppid): Keep on googletag.pubads(). Don't move it to googletag.setConfig().
  • googletag.setAdIframeTitle(title): Keep on googletag.
  • Third-party header bidding and non-GPT helpers: Leave calls such as pbjs.setConfig() and apstag.fetchBids() untouched, even when called through an alias.

來源與署名

來源:google/skills位於skills/ads/google-publisher-tag-migrate-to-setconfig提交35474ca

授權條款: 無授權條款

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

在 README 中新增徽章

向讀者展示該技能已收錄於 SourceWeft,徽章連結到本頁。

「Listed on SourceWeft」徽章預覽
[![Listed on SourceWeft](https://sourceweft.com/badge/skills/gh-google-skills-google-publisher-tag-migrate-to-setconfig-skills-ads-google-publisher-tag-migrate-to-setconfig-7771aa9da26090c4.svg)](https://sourceweft.com/skills/gh-google-skills-google-publisher-tag-migrate-to-setconfig-skills-ads-google-publisher-tag-migrate-to-setconfig-7771aa9da26090c4?utm_source=readme&utm_medium=badge)

檢舉或申請下架