我试图处理 iframe
中的 canvas
但我无法处理它。
它由 webgl
渲染,我想自动移动和滚动。
为了做到这一点,我尝试首先捕捉鼠标点击事件。 但它不起作用。
特别是,我无法更改 iframe
的内容,因为它是动态接收的。
- Is it possible?
- If it could be possible, please share the solution.
这是我的挑战。
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);
});
但它不起作用。
最佳答案
如果您的 iframe 来自另一个域,那您就不走运了。按照设计,主页不能直接操作来自不同域的 iframe,因为那将是一个巨大的安全问题。例如,一个页面可以在 iframe 中打开到 amazon.com,单击“添加到购物车”并单击“购买”。或者它可以监视 iframe 中的表单,在用户登录银行时监视用户的用户名和密码。这就是为什么如果子页面和父页面不在同一个域中,您将无法从父页面访问子页面(反之亦然)
所以首先您需要回答这个问题:您的 iframe 内容是否来自同一域?
如果您的 iframe 来自同一域,那么您需要等待 iframe 加载后再尝试访问其内容。
<!-- 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>
如果您的 iframe 来自不同的域,那么我知道的唯一解决方案是该 iframe 内容的创建者是否提供 API 来操作 iframe 的内容。例如Google maps offers an API to manipulate maps .如果您尝试显示的页面不提供 API,或者他们提供了 API 但不能满足您的需求,那么就没有解决方案。
关于javascript - 处理 iframe 内的 Canvas 元素,例如使用 javascript 自动移动和滚动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58518927/