目标:将变量从 Angular 应用程序发送到该页面上的 iFrame,但位于另一台服务器上
问题:为什么 document.getElementById 返回 null?我是在错误地使用 DomSanitizer 还是错误地使用了 postMessage?
(我试过的)
我把它放在 ngAfterViewInit 里面,所以它应该在正确的时间访问它
DevConsole错误显示:错误:资源 URL 上下文中使用的不安全值(请参阅http://g.co/ng/security#xss)
- 我阅读了它提到的文章(http://g.co/ng/security#xss)并应用了 DomSanitization SafeScript 返回一个值,这让我觉得我正确使用了 DomSanitizer。
然后我阅读(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');
}
}
聊天框.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>