Thunderbird AddOn for text replacement debugging

this is my first TB addOn development and I need a hint for debugging. The addOn is a kind of auto correction or auto text replacement. This means, you can save a shortcut like ‘br’ and it will replaced with ‘Br, John Doe’. This works automaticly and to this point everythings works fine.

But I would like to offer in setup the function to replace the shortcut if Enter-Key is pressed only. And here I have the problem, the cursor position, if enterReplace is active, aint got catched correctly and the replacement failed. I tried a lot, to asked ChatGPT was aint helpful as well.

This is the Code:

window.addEventListener("keydown", async (event) => {
    // Retrieve settings from local storage
    let setting_enter = await browser.storage.local.get({ enterReplace: false });

    // Get the current cursor position node
    let selection = window.getSelection();
    let range = selection.getRangeAt(0);
    let node = range.startContainer;

    // Only handle text nodes if Enter was not pressed
    if (node.nodeType !== Node.TEXT_NODE && event.code !== 'Enter') {
        return;
    }

    // Function for text replacement and HTML insertion
    const replaceText = async () => {
        console.log("Node text content:", node.textContent); // Debugging
        console.log("Cursor position (offset):", range.startOffset); // Debugging

        // Get text up to the cursor position in the current node
        let textBeforeCursor = node.textContent.slice(0, range.startOffset);
        console.log("Text before cursor:", textBeforeCursor); // Debugging

        // Capture the last word before the cursor
        let words = textBeforeCursor.trim().split(/s+/); // Split the text into words
        let wordToReplace = words[words.length - 1]; // The last word is what we want to replace

        console.log("Word to replace:", wordToReplace); // Debugging

        // Retrieve replacements from storage
        let data = await browser.storage.local.get({ replacements: [] });
        let replacements = data.replacements;

        // Check if the last word is a shortcut and should be replaced
        let shortcutFound = false; // Variable to determine if a shortcut was found
        for (let item of replacements) {
            console.log("Checking shortcut:", item.shortcut); // Debugging
            if (wordToReplace === item.shortcut) {
                shortcutFound = true; // Shortcut found
                // Replace line breaks with <br> for HTML context
                let replacementText = item.replacement.replace(/n/g, '<br>');

                // Replace text in the range
                let newText = textBeforeCursor.slice(0, -wordToReplace.length);

                // Remove old text up to the shortcut
                range.setStart(node, newText.length);
                range.setEnd(node, textBeforeCursor.length);
                range.deleteContents();

                // Insert HTML by creating a new Range object
                let fragment = document.createRange().createContextualFragment(replacementText);
                range.insertNode(fragment);

                // After inserting, set the cursor to the end of the inserted HTML
                range.collapse(false);
                selection.removeAllRanges();
                selection.addRange(range);
                break; // Break the loop after replacing the shortcut
            }
        }

        // If no shortcut was found, we can log a message here
        if (!shortcutFound) {
            console.log("No matching shortcut found for:", wordToReplace);
        }
    };

    // If 'enterReplace' is active and Enter is pressed
    if (setting_enter.enterReplace && event.code === 'Enter') {
        event.preventDefault(); // Prevent the default Enter key effect

        // Handle replacement and cursor position in one step
        await replaceText();

        // Optionally: add a new line break after the replacement is done
        let brNode = document.createElement("br");
        range.insertNode(brNode);
        range.collapse(false);  // Set the cursor to the end
        selection.removeAllRanges();
        selection.addRange(range);
    } else if (!setting_enter.enterReplace) {
        // Apply delay only if 'enterReplace' is not active
        setTimeout(async () => {
            // Recheck the current selection
            selection = window.getSelection();
            range = selection.getRangeAt(0);
            node = range.startContainer;

            await replaceText();
        }, 700);
    }
}); 

Where is the bug?

Thx!

autoReplace Setup

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật