FLASH SALE Get 20% OFF everything using the coupon code: FLASH20 View WordPress Plugins →

How to Add the Facebook Messenger Customer Chat to Your Site Using Google Tag Manager

on in Inbound Marketing, AJAX and Fetching Data
Last modified on

Facebook Messenger Customer Chat Plugin

Google Tag Manager is using its own Closure Compiler behind the scenes to compress the JavaScript and HTML code. It does not support ES6, so it’s pretty tricky to use ES6 code or non-standard HTML attributes, such as:

<div class="fb-customerchat" attribution=setup_tools page_id="1234567890123"></div>

The attribution parameter is particularly wrong, as the value is not within quotes.

Moving forward, we need to remove this HTML element completely and rebuild it using JavaScript:

<script>
// Create the DIV element dynamically to work around GTM
var chatDiv = document.createElement('div');
chatDiv.className = 'fb-customerchat';
chatDiv.setAttribute('page_id', '1234567890123');
document.body.appendChild(chatDiv);
</script>

Here’s a list of attributes you can use while building the JavaScript code.

You can also use the official Facebook Messenger plugin, but the advantage of Google Tag Manager is page targeting and rules.

Your final code should look like this:

<div id="fb-root"></div>
<script>
// Create the DIV element dynamically to work around GTM
var chatDiv = document.createElement('div');
chatDiv.className = 'fb-customerchat';
chatDiv.setAttribute('page_id', '1234567890123');
document.body.appendChild(chatDiv);

window.fbAsyncInit = function() {
    FB.init({
        xfbml: true,
        version: 'v8.0'
    });
};

(function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = 'https://connect.facebook.net/en_GB/sdk/xfbml.customerchat.js';
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>

Unrelated to this workaround, pay close attention not to have the <div id="fb-root"></div> element included twice and keep your Graph API – version: 'v8.0' – up to date.

Related posts