Search code examples
javascriptangulargoogle-chromeiframe

Post message to cross-origin iframe in JavaScript


I'm new to JavaScript, and I'm trying to post a message to my iframe in order to scroll it. I'm trying to achieve it using this code.

scroll(i) {
  var src = $("#iframe").attr("src");
  $("#iframe").contentWindow.postMessage(i, src);
}

This code is working when launched in Chrome console, but it is not working when launched from the Webapp (using a button).

I get an error saying contentWindow is undefined. Does someone know why?


Solution

  • For some reason it seems my code was managing $("#iframe") as an array. I got this issue solved by doing this:

    scroll(i) {
      var src = $("#iframe")[0].attr("src");
      $("#iframe")[0].contentWindow.postMessage(i, src);
    }