Is it possible to programmatically fire mouse events in DOM? My sample case would be the following:
<html>
<body>
<iframe style="width: 500px; height: 500px;" src="something.html"></iframe>
<div id="layer" style="position: absolute; left: 0px; top=0px; width=500px; height=500px;"></div>
</body>
</html>
Whenever the user clicks the div
over an iframe
, I would like to somehow propagate the event to the iframe
, too. (Here we assume that the iframe src
is in the same domai开发者_JS百科n.)
Whilst you can inject events into browsers' event-handling systems (in not entirely portable ways), it will only cause event handlers registered on those events to be called. It won't cause default actions like following clicked links. Also you don't get the target element worked out for you from co-ordinates so you'd have to do that yourself.
A better bet would be to lose the obscuring <div>
and register a click
handler on the iframe's document, which then informs code in the parent of the location of the click.
If you ever are in a situation, where you have <iframe>
s parent and child in different domains, I recommend learning to use postMessage()
.
With postMessage()
you can listen "message"
event like so:
window.addEventListener("message", (event) => {}
https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
I wanted to add this, because a while back, I had a hard time finding the best way to do it. Also, postMessage()
is useful in situations, when you want to control things, you want to listen in an iframe.
精彩评论