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

πŸ™‚ Like
πŸ™‚Like πŸ₯°Love 🧐Watching this 🀨Suspicious πŸ˜’Meh 😑Angry
πŸ™‚4πŸ₯°1πŸ˜’1
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.

Find more JavaScript tutorials, code snippets and samples here or more jQuery tutorials, code snippets and samples here.

Added by Ciprian on Tuesday, September 29, 2020 in Blog, JavaScript

Unlimited Automated Page Speed Monitoring & Tracking.
Use SpeedFactor to track your website. It’s simple and reliable.
See how real people experience the speed of your website. Then find (and fix) your web performance problems.
Get Started

Related Articles

%d bloggers like this:
Privacy Policy