Angular: Adding Custom Event Listeners to Dynamic Intercom Chatbot Iframe Elements Before Full Load

Currently, I am working on an Angular project in which I need to interact with dynamic iframe content of the Intercom chatbot. Particularly, my intention is to;

Insert custom event listeners into Intercom’s predefined inquiry queries.

When the preset questions are answered, add custom event listeners to the text area and send button for asking custom questions.

Due to the 15-second delay in response time by Intercom, make custom API calls.

The problem here is that I can’t attach these event listeners immediately because the iframe content loads dynamically and asynchronously. Even if it isn’t fully loaded, I need a way of attaching reliable event listeners to these elements as soon as the Intercom chatbot opens up within that iframe.

What I Tried:

  1. DOM Manipulation: Attempted to select the iframe and attach event listeners directly to its elements.

const intercomFrame = document.querySelector(‘iframe’);

intercomFrame.contentWindow.addEventListener(‘load’, () => {

const textarea = intercomFrame.contentDocument.querySelector(‘textarea’);

textarea.addEventListener(‘input’, () => {

// Custom logic here

});

}
);

  1. MutationObserver: Used MutationObserver to detect changes in the iframe’s DOM and attach event listeners once the elements are loaded.

const observer = new MutationObserver((mutations) => {

const textarea = intercomFrame.contentDocument.querySelector(‘textarea’);

if (textarea) {

textarea.addEventListener('input', () => {

  // Custom logic here

});

observer.disconnect();

}

});

const intercomFrame = document.querySelector(‘iframe’);

observer.observe(intercomFrame.contentDocument, { childList: true, subtree: true }
);

  1. Custom Angular Service:

import { Injectable, Renderer2, RendererFactory2 } from ‘@angular/core’;

import { fromEvent } from ‘rxjs’;

import { filter, map, switchMap } from ‘rxjs/operators’;

@Injectable({

providedIn: ‘root’,

})

export class IntercomService {

public timeoutId: any;

private renderer: Renderer2;

constructor(rendererFactory: RendererFactory2) {

this.renderer = rendererFactory.createRenderer(null, null);

}

public startMonitoringIframeAndHandleEvents(queryCacheId: string): void {

(window as any).textArea = '';

const loadChatBotPromptAPI = /* custom API call function */;

const iframe = document.querySelector('iframe[name="intercom-frame"]') as HTMLIFrameElement;



if (iframe) {

  const iframeDocument = iframe.contentDocument || iframe.contentWindow?.document;



  if (iframeDocument) {

    const sendButton = iframeDocument.querySelector('button.send-button-class');

    const suggestionsContainer = iframeDocument.querySelector('.suggestions-container-class');

    const textArea = iframeDocument.querySelector('.textarea-class');



    if (sendButton) {

      fromEvent(sendButton, 'click').pipe(

        map(() => (window as any).textArea),

        filter(userInput => userInput !== 'Custom Question Prompt'),

        switchMap(userInput => loadChatBotPromptAPI(queryCacheId, userInput))

      ).subscribe({

        next: () => {

          // Handle success if needed

        },

        error: () => {

          // Handle error

        },

      });

    }



    if (suggestionsContainer) {

      fromEvent(suggestionsContainer, 'click').pipe(

        map((event: Event) => (event.target as HTMLElement).textContent?.trim()),

        filter(userInput => userInput !== 'Custom Question Prompt'),

        switchMap(userInput => loadChatBotPromptAPI(queryCacheId, userInput))

      ).subscribe({

        next: () => {

          // Handle success if needed

        },

        error: () => {

          // Handle error

        },

      });

    }



    if (textArea) {

      fromEvent(textArea, 'change')

        .pipe(map(() => (textArea as HTMLElement).innerHTML))

        .subscribe((text) => {

          (window as any).textArea = text;

        });



      fromEvent(textArea, 'keyup')

        .pipe(filter((event: KeyboardEvent) => event.which === 13))

        .pipe(map(() => (window as any).textArea))

        .pipe(filter(userInput => userInput !== 'Custom Question Prompt'))

        .pipe(switchMap(userInput => loadChatBotPromptAPI(queryCacheId, userInput)))

        .subscribe({

          next: () => {

            // Handle success if needed

          },

          error: () => {

            // Handle error

          },

        });

    }

  }

}

}

}

What Actually Happened:

The content of iframe is loaded asynchronously, which causes lateness and inconsistency in attaching event listeners. In some instances, the listener is not attached successfully, thus giving unreliable behavior.

I would really appreciate it if you could help me attach these dynamic iframe elements to event listeners in a reliable manner.

New contributor

Yash Samtariya is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

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