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:
- 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
});
}
);
- 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 }
);
- 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.
Yash Samtariya is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.