Handle the canvas element inside the iframe such as moving and scrolling automatically using javascript?

Viewed 653

I tried to handle the canvas inside the iframe but I could not handle it. It is rendered by webgl and I want to move and scroll automatically.

In order to do it, I tried to catch the mouse click event firstly. But it is not working.

Especially, I could not change the contents of the iframe because it is received dynamically.

  1. Is it possible?
  2. If it could be possible, please share the solution.

This is my challenge.

let iframe = document.getElementById("childFrame");
let childDocument = iframe.contentWindow.document;
let canvas = childDocument.getElementById("map-canvas");
canvas.addEventListener('click', function (e) {
  console.log('#### DEBUG EVENT: ', e);
});

But it does not work.

1 Answers

If your iframe is from another domain you're out of luck. By design the main page can not directly manipulate iframes from a different domain as that would be a huge security issue. For example a page could open in iframe to amazon.com, click "add to cart" and click "buy". Or it could monitor the forms in the iframe watching for the user's username and password as they logged in to their bank. That is why if the child and parent pages are not on the same domain you can not access the child from the parent (nor vice-versa)

So first you need to answer the question: Is your iframe contents from the same domain?

If your iframe is from the same domain then you need to wait for the iframe to load before trying to access its content.

<!-- main.html -->
<body>
  <iframe id="childFrame"></iframe>
</body>
<script>
const iframe = document.getElementById("childFrame");
iframe.onload = run;
iframe.src="child.html";

function run() {
  const childDocument = iframe.contentWindow.document;
  const canvas = childDocument.getElementById("map-canvas");
  canvas.addEventListener('click', function (e) {
    console.log('#### DEBUG EVENT: ', e);
  });    
}
</script>
<!-- child.html -->
<p>
  click in side rect
</p>
<canvas id="map-canvas" width="200" height="50" style="border: 1px solid black"></canvas>

example

If your iframe is from a different domain then the only solution I know if is if the creator of the content of that iframe offers an API to manipulate the contents of the iframe. For example Google maps offers an API to manipulate maps. If the page you're trying to display does not offer an API or they do but it doesn't do what you need then there is no solution.

Related