I am trying to get AdSense setup in my Sapper built website but I have had no success. I have added the code to the template.html file and it works, but I will like to show this on a specific page using a component.
The goal is to show the Ad in the Resource page, on the sidebar (see image). The widget above it, is a component that is loaded by the index.svelte page, so I'll like to do the same for the Ad.
At the moment, I have the following:
template.html
<footer>
<!-- GoogleAdsence Script. -->
<div id="gAdsense-code" style="display: none;">
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-X0X0X0X0X0X0X" crossorigin="anonymous"></script>
<!-- Resource page Ad -->
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-X0X0X0X0X0X0X"
data-ad-slot="X0X0X0X0X0X0"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
</footer>
adswidget.svelte
<script>
import { onMount } from 'svelte';
onMount(() => {
window.addEventListener( 'load', () => {
//get ads-widget div
let adWidget = document.getElementById('ads-widget');
let adCode = document.getElementById('gAdsense-code');
let adHtml = adCode.innerHTML;
adCode.remove();
//append Adsence code from the head on resources index file
adWidget.innerHTML = adHtml;
});
});
</script>
<div id="ads-widget"><!-- Adsence code inserted onMount --></div>
This will place the Adsense code in the right place, but the Ad will not display. The error I get on the console is: "adsbygoogle.push() error: No slot size for availableWidth=0" (see image) console error
I have also referenced this article w/o success.
Any help would be greatly appreciated :)
After coming across an article that shows how to implement Adsense in React I was able to adapt it to work in Svelte. So, posting the answer in case it helps anyone else:
template.html
...
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-X0X0X0X0X0X0X" crossorigin="anonymous"></script>
</body>
</html>
Place the 'adsbygoogle' code inside the component's OnMount() function. But, with a slight modification. Instead of (adsbygoogle = window.adsbygoogle ...)
you would do (window.adsbygoogle = window.adsbygoogle ...)
Also, add the <ins>
tag inside the same component after your styles. So the file would look something like this:
AdsWidget.svelte
<script>
onMount(() => {
(window.adsbygoogle = window.adsbygoogle || []).push({});
});
</script>
<style>
...
</style>
<div class="ads-widget-container">
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-X0X0X0X0X0X0X"
data-ad-slot="X0X0X0X0X0X0"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
</div>
And thats all. Hope this helps someone save some time.