目标:将变量从Angular应用程序发送到该页面上的iFrame,但位于另一台服务器上
问题:为什么document.getElementById返回null?我是错误使用DomSanitizer还是postMessage错误?
(我尝试过的)
我将其放在ngAfterViewInit内,因此应该在以下位置访问它 正确的时间
DevConsole 错误显示:错误:资源中使用的不安全值 URL上下文(请参见http://g.co/ng/security#xss)
然后我读 (https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage#Security_concerns) 并确保对event.origin进行检查
角度(本地主机: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 (本地主机: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>