Goal: Send variable from Angular application to iFrame on that page but living on another server
Question: Why is document.getElementById returning null? Am I using DomSanitizer incorrectly or postMessage incorrectly?
(What I've tried)
I placed it inside ngAfterViewInit so It should be accessing it at the correct time
DevConsole error shows: Error: unsafe value used in a resource URL context (see http://g.co/ng/security#xss)
- I read the article it mentioned (http://g.co/ng/security#xss) and applied DomSanitization SafeScript returns a value, which makes me think I am using DomSanitizer correctly.
I then read (https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage#Security_concerns) and made sure to do a check on event.origin
Angular(localhost:4200)
chat.component.html:
<div class="iframe-container">
<iframe id="iframe_chatui" src="{{ chatURL }}/loading.html" class="chatiframe" allow="microphone; camera"></iframe>
</div>
chat.component.ts:
const isIFrame = (input: HTMLElement | null): input is HTMLIFrameElement =>
input !== null && input.tagName === 'IFRAME';
ngAfterViewInit() {
this.safeScript = this.domSanitizer.bypassSecurityTrustScript(this.localeId);
let frame = document.getElementById('iframe_chatui');
if (isIFrame(frame) && frame.contentWindow) {
frame.contentWindow.postMessage(this.localeId, 'http://localhost:4200');
}
}
chatbox.aspx(localhost:7078):
<html>
<body onload="onLoad()" onresize="onResize()" style="overflow-x: hidden;">
<div id="ChatPanel" class="patient-chat" >
<div id="LiveChatLog" class="ChatLogBox"></div>
<div id="UserEntryBar" class="UserEntryBar">
<div id="divFileUpload">
<button id="btnAddImage" onclick="ShowImageSourceDialog()" title="Add Image"><i class="icon-camera"></i></button>
</div>
</div>
<div id="divEndVisit" style="display:none;" >
<button id="btnEndVisit" class="EndVisitButton btn" onclick="ConfirmEndVisitRequest();" >End Visit</button>
</div>
<div class="clearfix"></div>
</div>
<script type="text/javascript">
function receiveMessage(event)
{
try
{
if (event.origin === "[ROOT_SITE_URL]" ||
event.origin === "[ROOT_CHAT_SITE_URL]" ||
event.origin === "http://localhost:4200")
{
}
var receiveChatMsg = function (message)
{
if(randomCondition) {}
else if(desiredCondition) { window.addEventListener("message", receiveMessage, false); }
</script>
</body>
</html>