LoginSignup
3
1

More than 3 years have passed since last update.

ブラウザのXMLHttpRequest(xhr)でSlackとDiscordのWebhook URLにPOSTするサンプル

Posted at

最近触っていて、それっぽい簡易サンプルがなかったのでメモしておきます。

jQueryやaxiosでやっても良いのですが、xhrでシンプルに。

to Slack

Slackはこれまでのincoming webhookと作り方が変わったのでSlack側の設定で苦戦するかも。

function toSlack(message) {
    const url = 'Webhook URL';
    const data = {
        text: message
    };

    const xhr = new XMLHttpRequest();
    xhr.open("POST", url, false);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
    xhr.send('payload=' + JSON.stringify(data))
}

const msg = `hello slack~`;
toSlack(msg); //実行

to Discord

Discrodは割とシンプルです。

Slackのapplication/x-www-form-urlencodedとは違い、application/jsonで送ります。(むしろこっちの方が多いか)

function toDiscord(message){
    const url = 'Webhook URL';
    const data = {
        content: message
    };

    const xhr = new XMLHttpRequest();
    xhr.open("POST", url, false);
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.send(JSON.stringify(data))
}

const msg = `hello discord~`;
toDiscord(msg); //実行
3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1