🧩

GPT迁移setConfig

google-publisher-tag-migrate-to-setconfig · v
作者 google 公开目录收录

简介

将网页发布者代码从已弃用的Google Publisher Tag setter/getter方法迁移到setConfig()和getConfig()。适用于审计、更新或重构GPT代码。

原始描述

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, update

通过你的 Agent 添加

安装目录:google-publisher-tag-migrate-to-setconfig/(目录名取自 SKILL.md 的 frontmatter name,不是 URL 里的 slug)。

点「快速安装」复制一段指令贴给你的 Agent:它会先下载到 /tmp、把文件清单和校验值给你看,你确认之后才解压安装。不会一步装完、也不改系统其它位置。

或者手动安装

Claude Code~/.claude/skills/google-publisher-tag-migrate-to-setconfig/
Codex CLI~/.codex/skills/google-publisher-tag-migrate-to-setconfig/
DeepSeek Harness~/.agents/skills/google-publisher-tag-migrate-to-setconfig/

包是「根级 SKILL.md + 作者附带的文件」,解压到上面的 <slug>/ 目录即可; 目录名不用换,也不要把包直接解压到 skills 根目录。 技能申请的权限由作者决定:装之前先看清单里有没有脚本、它会读写什么。

技能正文


name: google-publisher-tag-migrate-to-setconfig description: >- 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. metadata: version: "1.0.0" publisher: google category: GoogleAds

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:

Setting Separate calls Clear one entry Clear everything
targeting, adsenseAttributes Merge keys { [key]: null } null
categoryExclusion Append unique non-empty labels; [] is a no-op Not supported null
  • 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

Feature Legacy googletag.pubads() call Replacement
AdSense attributes set(key, value) googletag.setConfig({ adsenseAttributes: { [key]: value } })
Category exclusion (add) setCategoryExclusion(label) googletag.setConfig({ categoryExclusion: [label] })
Category exclusion (clear) clearCategoryExclusions() googletag.setConfig({ categoryExclusion: null })
Centering setCentering(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 load disableInitialLoad() googletag.setConfig({ disableInitialLoad: true })
Single Request Architecture enableSingleRequest() googletag.setConfig({ singleRequest: true })
Lazy loading (defaults) enableLazyLoad() googletag.setConfig({ lazyLoad: {} })
Lazy loading (custom) enableLazyLoad(config) googletag.setConfig({ lazyLoad: config === undefined ? {} : config })
Geographic location setLocation(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() call Replacement
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

Feature Legacy Slot call Replacement
AdSense attributes slot.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 call Replacement
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() call Replacement
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.

正文来自原始仓库, 版权归作者所有,许可:Apache-2.0。 权利人认为有不妥,可申请下架。

原始仓库

作者的项目地址:https://github.com/google/skills

标签

没有标签

同类 Skill