Blogger网站通过JavaScript实现AdSense自定义广告投放需求
解决Blogger替换特定文本为自定义AdSense广告的方案
核心思路
通过JavaScript遍历文章内容的文本节点,精准定位标记文本showadshere,将其替换为自定义AdSense广告代码,避免自动广告破坏排版。
实现步骤及代码
定位文章内容容器
Blogger默认的文章内容区域通常带有.post-body或.entry-content类名,可通过浏览器开发者工具(F12)确认你的模板使用的选择器。编写替换脚本
将以下代码添加到Blogger模板的</body>标签之前:function replaceTextWithAd() { // 替换为你的文章内容容器选择器 const postContent = document.querySelector('.post-body'); if (!postContent) return; function traverseNodes(node) { if (node.nodeType === Node.TEXT_NODE) { const text = node.textContent; const adMarker = 'showadshere'; if (text.includes(adMarker)) { const parts = text.split(adMarker); const fragment = document.createDocumentFragment(); fragment.appendChild(document.createTextNode(parts[0])); // 创建广告容器,替换为你的AdSense代码 const adContainer = document.createElement('div'); adContainer.style.margin = '20px 0'; // 可自定义广告上下间距,优化排版 adContainer.innerHTML = ` <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-你的发布者ID" crossorigin="anonymous"></script> <!-- 自定义广告单元 --> <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-你的发布者ID" data-ad-slot="你的广告单元ID" data-ad-format="auto" data-full-width-responsive="true"></ins> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script> `; fragment.appendChild(adContainer); if (parts[1]) { fragment.appendChild(document.createTextNode(parts[1])); } node.parentNode.replaceChild(fragment, node); } } else if (node.nodeType === Node.ELEMENT_NODE && node.tagName !== 'SCRIPT' && node.tagName !== 'STYLE') { for (let i = 0; i < node.childNodes.length; i++) { traverseNodes(node.childNodes[i]); } } } traverseNodes(postContent); } // 页面加载完成后执行替换 window.addEventListener('DOMContentLoaded', replaceTextWithAd);
关键注意事项
- 替换选择器:如果
.post-body无法定位内容,替换为你的模板实际使用的类名或ID。 - AdSense代码适配:将代码中的
ca-pub-你的发布者ID和你的广告单元ID替换为你自己的信息,确保广告代码是AdSense提供的异步版本。 - 排版优化:可通过修改
adContainer.style调整广告的边距、对齐方式,让广告与文章内容更协调。 - 动态加载适配:如果你的Blogger采用滚动加载更多文章的模式,需要在新文章渲染完成后再次调用
replaceTextWithAd()函数。
内容的提问来源于stack exchange,提问作者utzlol
相关产品推荐
相关产品推荐

