{ mutations.forEach(mutation => { // Log the added nod"> { mutations.forEach(mutation => { // Log the added nod"> { mutations.forEach(mutation => { // Log the added nod">
const intervalId = setInterval(() => {
    const iframe = document.querySelector("#chatframe");

    // Step 2: If the iframe exists, clear the interval and set up the observer
    if (iframe) {
        clearInterval(intervalId);  // Stop checking once iframe is found

        // Step 3: Once iframe is found, call a separate function to set up the observer
        setupObserver(iframe);
    }
}, 1000);  // Check every 1 second (1000ms)

// Step 4: Separate function to set up the MutationObserver inside the iframe
function setupObserver(iframe) {
    // Access the iframe's content document
    const iframeDocument = iframe.contentDocument || iframe.contentWindow.document;

    // Find the #items element inside the iframe
    const itemsElement = iframeDocument.querySelector("#items");

    if (itemsElement) {
        // Set up the MutationObserver
        const observer = new MutationObserver(mutations => {
            mutations.forEach(mutation => {
                // Log the added nodes (new child elements)
                if (mutation.type === "childList") {
                    mutation.addedNodes.forEach(addedNode => {
                        if (addedNode.nodeType === Node.ELEMENT_NODE) {
                            // Check if #message exists in the addedNode
                            let targetNode = addedNode.querySelector("#message");

                            // If #message is found, save position of all nodes inside it
                            if (targetNode) {
                                saveNodePositions(targetNode);
                            }
                        }
                    });
                }
            });
        });

        // Start observing the #items element for changes (child additions)
        observer.observe(itemsElement, {
            childList: true,  // Observe child additions/removals
            subtree: false     // Observe the entire subtree inside #items
        });

        console.log('Observer set up successfully for #items inside iframe.');
    } else {
        console.log('No element with id="items" found inside the iframe.');
    }
}

// Function to save and print the position of text and <img> nodes inside #message
function saveNodePositions(targetNode) {
    // Get all child nodes (text and <img> elements) inside targetNode
    const childNodes = targetNode.childNodes;
    
    childNodes.forEach((node, index) => {
        // Save the position of each node (text or <img>) inside the #message
        if (node.nodeType === Node.TEXT_NODE) {
            console.log(`Text Node at position ${index}: "${node.textContent.trim()}"`);
        } else if (node.nodeName === "IMG") {
            console.log(`IMG Node at position ${index}:`, node);
        }
    });
}