How to post to Slack using a third-party script

Or Google Tag Manager, whichever is handier.

Here’s a short snippet of code I used to use to notify my team of recent conversions, as they took place. The delay was less than 3 seconds.

Slack Logos
const url = 'https://hooks.slack.com/services/XXXXXXXXX/YYYYYYYYY/ZZZZZZZZZZZZZZZZZZZZZZ';
const text = 'New event - {{customEventId}} - completed!';

fetch(url, {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({ text: text })
})
.then(response => {
    if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response.json();
})
.then(data => {
    console.log('Success:', data);
})
.catch(error => {
    console.error('Error:', error);
});

Notes & Details

  1. Get the hook URL from Slack.
  2. {{customEventId}} is a Google Tag Manager variable.

on in Blog | Last modified on

Related Posts