How to Setup Google Adsense in Discourse

Introduction

Once you have a good traffic discourse website, the next step to bring up some revenue is by setting up advertisements on your website.

This article describes the steps to configure google AdSense advertisement in Discourse website.

Pre-requisites

  1. Approved Google Adsense account
  2. Approve website in Google Adsense account.

Install Official Discourse Ad Plugin

In /var/discourse/containers/app.yaml add the following lines under the after_code hooks section.

$ cd /var/discourse
$ sudo vi app.yaml
hooks:
  after_code:
    - exec:
        cd: $home/plugins
        cmd:
          - git clone https://github.com/discourse/discourse-adplugin.git 
git pull
sudo ./launcher rebuild app

Configure Content Security Policy To Load Google Ads

Discourse by default blocks loading resources from other hosts. This will block loading ads from the Google AdSense domain. You may notice the below error in network logs in such cases.

Content Security Policy: The page’s settings blocked the loading of a resource at 
https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js (“script-src”).

To enable resources from google Adsense hosts in Discourse, search for content security policy script src on the Settings page or Navigate to the Security section on the Settings page.

Add the following values to the content security policy script src parameter.

  1. 'unsafe-inline'
  2. https

Configure Adsense In Discourse

Once the build is completed, log in to your discourse admin dashboard and navigate to the Settings tab and search for Adsense.

Fill in the AdSense publisher code and Ad unit details.

Note: Exlclude pub- from the Adsense Published ID while entering.

The Published ID will be available on the Accounts page of your Google Adsense account.

The ad code can be obtained from the ad embed code in the Google Adsense ad unit setting page.

For example, from the google ad embed code below, the code to be entered in discourse is x8082xxxxx

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-xxxxxxxxxxxxxx"
     crossorigin="anonymous"></script>
<!-- forum.debugfactor.com-top-list-top -->
<ins class="adsbygoogle"
     style="display:block"
     data-ad-client="ca-pub-xxxxxxxxxxxxxx"
     data-ad-slot="x8082xxxxx"
     data-ad-format="auto"
     data-full-width-responsive="true"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
Note that it might take a while for the advertisement to appear on your website. Till then, you will just see a placeholder text  'ADVERTISEMENT'
Admin

Admin