| <!DOCTYPE html> |
| <style> |
| .target { |
| position: fixed; |
| top: 100px; |
| left: 25px; |
| width: 100px; |
| height: 100px; |
| background-color: red; |
| } |
| .spacer { |
| height: 1000px; |
| } |
| </style> |
| <div class='spacer'></div> |
| <div id='target' class='target'></div> |
| <script> |
| function clientRectToJson(rect) { |
| if (!rect) |
| return "null"; |
| return { |
| top: rect.top, |
| right: rect.right, |
| bottom: rect.bottom, |
| left: rect.left |
| }; |
| } |
| function entryToJson(entry) { |
| return { |
| time: entry.time, |
| callbackTime: performance.now(), |
| boundingClientRect: clientRectToJson(entry.boundingClientRect), |
| intersectionRect: clientRectToJson(entry.intersectionRect), |
| rootBounds: clientRectToJson(entry.rootBounds), |
| target: entry.target.id |
| }; |
| } |
| onload = () => { |
| let target = document.getElementById("target"); |
| let observer = new IntersectionObserver(entries => { |
| entries.map(e => { window.parent.postMessage(entryToJson(e), "*") }); |
| }); |
| |
| window.addEventListener("message", event => { |
| observer.observe(document.getElementById("target")); |
| }); |
| |
| }; |
| </script> |