2

Goal/Background: I need to send the value of a variable from my Angular application to the ChatServer(aspx with javascript) that is inside an iFrame on the page. It is on a different server.

What I've tried: I am following the workaround here: https://stackoverflow.com/a/25098153/11187561

However, I am getting the error: Property 'contentWindow' does not exist on type HTMLElement

What else i've tried next: Looking through SO, I found https://stackoverflow.com/a/38457886/11187561

I placed it in ngAfterViewInit but I am still getting the error.

Code:

ngAfterViewInit() {
    var frame = document.getElementById('your-frame-id');
    frame.contentWindow.postMessage(/*any variable or object here*/, '*'); 
}
sideshowbarker
  • 62,215
  • 21
  • 143
  • 153
angleUr
  • 207
  • 2
  • 13

1 Answers1

6

The problem is that getElementById returns an HTMLElement not an HtmlIFrameElement. What you can do is define a type guard to check that the frame is an IFRAME. A secondary problem is that contentWindow can be null, so we also must check that.

const isIFrame = (input: HTMLElement | null): input is HTMLIFrameElement =>
    input !== null && input.tagName === 'IFRAME';

function ngAfterViewInit() {
    let frame = document.getElementById('your-frame-id');
    if (isIFrame(frame) && frame.contentWindow) {
        frame.contentWindow.postMessage({}, '*');
    }
}
Shaun Luttin
  • 107,550
  • 65
  • 332
  • 414
  • Thanks. This does result in the following error though: "Error: unsafe value used in a resource URL context." I am reading up about XSS to see how to avoid this – angleUr Jun 12 '19 at 15:39
  • @angleUr Have you read the MDN page? It's usually helpful for me. https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage#Security_concerns You're no longer experiencing an error with TypeScript but instead an error with how the `postMessage` API works. – Shaun Luttin Jun 12 '19 at 15:51
  • 1
    I see this deserves a separate post as the error is different now. I looked through the documentation and updated my code in a separate thread – angleUr Jun 12 '19 at 23:04