注:プライバシー保護のため、データをマスキングしています。
以下の情報を提供する API 応答があります。また、API 応答は動的であるため、ビジネス要件に応じて、2 つまたは 20 の広告スロット情報を取得します。
{
"googletags":[
{
"networkId":"xyz",
"targetedAdUnit":"Test_Offers_1",
"adSlotCreativeSize":[
[
336,
280
],
[
320,
100
]
],
"divGPTId":"div-gpt-ad-1"
},
{
"networkId":"xyz",
"targetedAdUnit":"Test_Offers_2",
"adSlotCreativeSize":[
[
336,
280
],
[
320,
100
]
],
"divGPTId":"div-gpt-ad-2"
}
.
.
.
.
.
.
.
.
{
"networkId":"xyz",
"targetedAdUnit":"Test_Offers_n",
"adSlotCreativeSize":[
[
336,
280
],
[
320,
100
]
],
"divGPTId":"div-gpt-ad-n"
}
]
}
この応答を使用して、実行時にスロットを定義しています。
JavaScript コード:
window.googletag = window.googletag || { cmd: [] };
function googleTags(url, cFunction) {
const xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
cFunction(this);
}
};
xhttp.open('GET', url, true);
xhttp.send();
}
function pushGTMtags(xhttp) {
const tags = JSON.parse(xhttp.responseText)['googletags'];
window.googletag.cmd.push(function () {
for (let i = 0; i < tags.length; i++) {
const str = `/${tags[i].networkId}/${tags[i].targetedAdUnit}`;
const adSlotCreativeSize = tags[i].adSlotCreativeSize;
const divGPTId = tags[i].divGPTId;
window.googletag
.defineSlot(
str,
adSlotCreativeSize,
divGPTId
)
.addService(window.googletag.pubads());
}
window.googletag.pubads().enableSingleRequest();
window.googletag.pubads().collapseEmptyDivs();
window.googletag.enableServices();
});
}
googleTags('apiUrl', pushGTMtags);
HTML : この HTML は、divGPTId で動的に反復していると考えてください。以下はほんの一例です。API response.length に基づいて div を反復処理しています。
<div class="slot " id="div-gpt-ad-0">
<script>
googletag.cmd.push(function () {
googletag.display('div-gpt-ad-0');
});
</script>
</div>
上記のコードを実際の詳細で実行した後、ブラウザー コンソールにコード エラーは表示されません。また、ページに広告が表示されません。何か不足していますか?
ブラウザでデバッグを試みましたが、エラーは発生しません。