Issue
I'm trying to embed a chatbot (Angular 14 app) in an iframe and this works. The next stage is to detect if the frame inside should be minimized. This is needed to style it for fitting the parent container. I wish to send custom events to the receiving frame.
let iframeCanvas = document.querySelector("iframe").contentWindow.document.querySelector("canvas"); // canvas is where the image is placed for click events
Angular embedded page component:
<app-avatar #avatar (click)="toggle_chat()" [embedded]=true></app-avatar>
I have created an @Output()
event: @Output() isOpen = new EventEmitter<boolean>();
When clicking on the avatar the toggle_chat()
function will emit the event: this.isOpen.emit(false); // testing if the value can be accessed from a vanillaJS page
The issue is I can't access events emitted from Angular. How can I receive these events on the parent page? The events are jailed inside of the <iframe src="...angular app.." .. />
and so to receive messages and send messages to the iframe event emitters are needed.
A more clear picture of the issue is this structure:
<!doctype html>
<body>
...
<script>
// Receive events from the iframe below
let iframeCanvas = document.querySelector("iframe").contentWindow.document.querySelector("canvas");
// Somehow access the iframeCanvas and listen for events
if(iframeCanvas.isOpen) document.getElementById("chat-app-frame").classList.toggle('full-size-chat-window'); // Show the full size chat window
</script>
<iframe id="chat-app-frame" src="...angular/chatapp/index.html" frameborder="0" scrolling="no" style="position:fixed;right:0;bottom:0; height:50%;width:400px;"></iframe>
</body>
</html>
Solution
I found the solution. When trying to interact with iframe's that do not belong the the origin will not work. The workaround is to use the window.postMessage
api.
You can learn more about this API here. Interacting with iFrames requires sending messages between windows and the postMessage API is bi-directional.
Answered By - Kyle
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.