Streamlabs’ Chatbox JavaScript – Random name color

From: streamlabs-chatbox_random-name-color.js

Array.prototype.shuffle = function() {
    return this.sort(() => Math.random() - 0.5);
}

// Random value to concat to name.
// Personal reason: due to relevant names matching the same indexed element.
// This might also make the following shuffle unnecessary.
const randomConcat = Math.random();

const nameColorOverrides = {
    'John': '#FF0000',
};

const colors = [ // List of twitch default colors
    "Blue",
    "Coral",
    "DodgerBlue",
    "SpringGreen",
    "YellowGreen",
    "Green",
    "OrangeRed",
    "Red",
    "GoldenRod",
    "HotPink",
    "CadetBlue",
    "SeaGreen",
    "Chocolate",
    "BlueViolet",
    "Firebrick",
].shuffle(); // Shuffle array to get a random color each time the script runs

String.prototype.toColor = function() {
    var hash = 0;
    if (this.length === 0) return hash;
    for (var i = 0; i < this.length; i++) {
        hash = this.charCodeAt(i) + ((hash << 5) - hash);
        hash = hash & hash;
    }
    let index = ((hash % colors.length) + colors.length) % colors.length;
    return colors[index];
}

//
// Streamlabs listeners
//

// Please use event listeners to run functions.

document.addEventListener('onLoad', function(obj) {
    // obj will be empty for chat widget
    // this will fire only once when the widget loads
});

document.addEventListener('onEventReceived', function(obj) {
    // obj will contain information about the event

    // Select all messages since obj.details.messageId does not work on YT Live Streams
    for (let message of document.querySelectorAll('#log [data-from]')) {
        var color;

        if (nameColorOverrides[message.dataset.from]) {
            color = nameColorOverrides[message.dataset.from];
        } else {
            color = message.dataset.from.concat(randomConcat).toColor();
        }
        
        message.querySelector('span.meta').style.color = color;
    }
});

Author: Fajrul

Amateur physicist and science writer