Get alert after click inside iframe, by jQuery Or javascript

旧时模样 提交于 2019-12-13 07:35:41

问题


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.



来源:https://stackoverflow.com/questions/28968516/get-alert-after-click-inside-iframe-by-jquery-or-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!