'Chrome Extension - Not able to add an element to Gmail Compose window

I'm building a Google Chrome extension that will add a checkbox to the Compose/Reply window in Gmail. But the console is giving me an error message that it can't read the properties of appendChild (the function I'm using to add this checkbox to the window).

Here's my manifest.json:

"content_scripts": [
    {
        "matches": ["https://mail.google.com/mail/*"],
        "run_at": "document_idle",
        "js": ["contentScript.js"]
    }
],

"permissions": [  
    "tabs",
    "https://mail.google.com/*",
    "storage"      
  ]

And here is the relevant parts of my contentScript.js file, where the majority of my code is:

// Listen for Reply arrow (top reply) click
let topReplyButton = document.getElementsByClassName('T-I J-J5-Ji T-I-Js-IF aaq T-I-ax7 L3');
topReplyButton[0].addEventListener("click", addUpdateButton);

function addUpdateButton() {
    let optionsArea = document.getElementsByClassName("aDh");
    if (optionsArea) {
        let mauticLabel = document.createElement('label');
        mauticLabel.setAttribute('name','mauticLabel');
        mauticLabel.innerHTML = "Track with Mautic: ";
        mauticLabel.setAttribute('id','mauticLabel');
        optionsArea[0].appendChild(mauticLabel);

And this is the error I get in the console when I click the reply button:

Uncaught TypeError: Cannot read properties of undefined (reading 'appendChild')
at HTMLDivElement.addUpdateButton

So something seems to be wrong from the point when I create mauticLabel, but I haven't been able to figure out what's breaking.

Thanks in advance :)



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source