Skip to content

Commit 0c13b0b

Browse files
committed
H2Ad
1 parent 65af780 commit 0c13b0b

2 files changed

Lines changed: 36 additions & 19 deletions

File tree

src/components/ads/InArticleAd.astro

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,6 @@
44

55
<div class="in-article-ad-container">
66
<span class="ad-label">Advertisement</span>
7-
<script
8-
async
9-
src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-7993314093599705"
10-
crossorigin="anonymous"></script>
117
<ins
128
class="adsbygoogle"
139
style="display:block; text-align:center;"
@@ -19,6 +15,7 @@
1915

2016
<style>
2117
.in-article-ad-container {
18+
display: none; /* Hidden by default, shown via script for specific instances */
2219
margin: 2rem 0;
2320
text-align: center;
2421
overflow: hidden;

src/pages/blog/[...slug].astro

Lines changed: 35 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,7 @@ const components = {
183183
Arrow,
184184
Underline,
185185
Aside,
186-
// h2: H2Ad,
186+
h2: H2Ad,
187187
};
188188
---
189189

@@ -238,22 +238,42 @@ const components = {
238238

239239
<ShareButtons title={post.data.title} url={url!} />
240240

241-
<div id="in-article-ad-source" style="display: none;">
242-
<InArticleAd />
243-
</div>
241+
<script
242+
async
243+
src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-7993314093599705"
244+
crossorigin="anonymous">
245+
</script>
244246

245247
<script>
246-
import { insertAd } from "../../scripts/insertAd";
247-
248-
function initAd() {
249-
insertAd('.prose', 'in-article-ad-source');
250-
}
251-
252-
if (document.readyState === 'loading') {
253-
document.addEventListener('DOMContentLoaded', initAd);
254-
} else {
255-
initAd();
256-
}
248+
document.addEventListener("DOMContentLoaded", () => {
249+
const ads = document.querySelectorAll('.in-article-ad-container');
250+
let targetAd: Element | null = null;
251+
252+
if (ads.length >= 3) {
253+
// Priority 1: Before 3rd heading (index 2)
254+
targetAd = ads[2];
255+
console.log("H2Ad: Activating ad before 3rd heading");
256+
} else if (ads.length >= 1) {
257+
// Priority 2: Before 1st heading (index 0)
258+
targetAd = ads[0];
259+
console.log("H2Ad: Activating ad before 1st heading");
260+
}
261+
262+
if (targetAd) {
263+
// Show the ad
264+
(targetAd as HTMLElement).style.display = 'block';
265+
266+
// Trigger AdSense
267+
try {
268+
console.log("H2Ad: Pushing to adsbygoogle");
269+
((window as any).adsbygoogle = (window as any).adsbygoogle || []).push({});
270+
} catch (e) {
271+
console.error("H2Ad: AdSense push failed", e);
272+
}
273+
} else {
274+
console.log("H2Ad: No suitable headings found for ad placement");
275+
}
276+
});
257277
</script>
258278

259279
{relatedPostsToShow.length > 0 && (

0 commit comments

Comments
 (0)