Get alert after click inside iframe, by jQuery Or

2019-09-06 12:15发布

问题:

I want after click inside iframe get alert ok, i tried as following code but it don't work. what do i do?

I can not change the iframe, It is fixed.

HTML:

<div class="addv">
<iframe src="http://ad.anetwork.ir/showad/c.php?adwidth=300&amp;adheight=250&amp;aduser=1423687058" height="250" width="300" frameborder="0" scrolling="no" style="background: #FFF url(http://static-cdn.anetwork.ir/img/loader.gif) no-repeat center;"></iframe>
</div>

Jquery:

$(".addv").on("click", "a", function(event) {
    alert('ok'); //should alert ok
});

DEMO: http://jsfiddle.net/dky6h1ev/

回答1:

If I'm not mistaken, you're attempting to bind an event handler to an a tag that has been rendered as part of the DOM of the iframe. Unfortunately, this isn't possible given the fact the DOM has originated from a different domain.

You need a certain level of access to manipulate the child iframe's DOM, a level of access the same-origin policy prohibits you from:

The same-origin policy restricts how a document or script loaded from one origin can interact with a resource from another origin. Same-origin Policy is used as a means to prevent some of the Cross-site Request Forgery attacks.

https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy

It's a nuisance at times to try and work around this, but it's vital for security purposes.

If the iframe is on the same domain, you have options - but I'm assuming from your absolute URL (and it's at least the case in your fiddle), that it's on a different domain.



回答2:

Try to put an onClick = "alert('ok')" inside the iframe tag.