0

I have a div inside an iframe (no problems with origin policy as both the documents are from same application/domain). I need to figure out the distance of the div from parent window top. The iframe also has scrollbar, so that's one thing to consider too.

I can't produce a semi-working jsfiddle because of the cross origin policies (iframe.contentWindow won't be available), but here's the non-working fiddle anyway.

I have an embedded iframe in the fiddle:

<iframe src="https://noc2spam.github.io/embed.html?ddd" style="display:block; border:0; width:300px; height:200px; overflow:scroll"></iframe>

The following screenshot might give you an idea of what I exactly need.

no description

I have already tried some of the answers which do not seem work for iframes. As for example, this does not work. What is the most convenient way of doing this?

Gogol BH Network
  • 2,944
  • 4
  • 27
  • 52

1 Answers1

0

In order to get the offset from top of the div contained in the iframe you have to SUM the DIV offset inside the IFRAME to the offset of the IFRAME inside the mainWindow. To do so in Jquery (and postMessage between iframe and MainWindow):

/**
supposed:
#example-iframe = id of iframe
#example-div = id of DIV inside the iframe
*/
/** main.html -- top page */
$("#example-iframe")[0].contentWindow.postMessage({
  cmd:"getDivDistance"
});
window.onmessage = function(e){
  var msg = JSON.parse(e.data)
    switch(msg.cmd){
      case "setDivDistance":
        var frametop = $("#example-iframe").offset().top
        var totaltop = frametop + msg.top;
        alert("MY TOP IS "+totaltop);
      break;
    }
};


/** frame.html -- iframe page*/
window.onmessage = function(e){
    var msg = JSON.parse(e.data)
    switch(msg.cmd){
      case "getDivDistance":
        window.top.postMessage({
          cmd:"setDivDistance",
          top:$("#example-div").offest().top
         });
      break;
    }
}
MadPapo
  • 485
  • 4
  • 12
  • Let me try this out.. if it works, I will accept the solution :) – Gogol BH Network Jun 28 '17 at 12:33
  • This work also in crossOrigin iframe (because of the postMessage) – MadPapo Jun 28 '17 at 12:51
  • Not quite. Had to change the way I was trying to get it work. First thing I missed was the fact that I needed to compare with mouse pageY, not clientY (not in the scope of this question).. then.. I needed to take in account the scrollTop() of the iframe to find the scroll amount :) – Gogol BH Network Jul 03 '17 at 04:19