jQuery Click Tracking not working on iFrame

2019-07-25 00:55发布

First, here is my code:

<script type="text/javascript">
    $('#Advertisement-1').click(function () { 
        alert("Ad Clicked!"); 
    });
</script>

<div id="Advertisement-1">
    <!-- PBBG Ads Zone Code Begin -->
    <center>
        <iframe src='http://www.pbbgads.com/ad.php?z=429&bg=000000' width='468' height='67' marginwidth='0' marginheight='0' hspace='0' vspace='0' frameborder='0' scrolling='no'></iframe>
    </center>
    <!-- PBBG Ads Zone Code End -->
</div>

Now, my issue is when I click the ad, it doesn't send an alert. It just opens the ad in a new window. Any ideas how I can get the click event to work?

3条回答
男人必须洒脱
2楼-- · 2019-07-25 01:32

click event doesn't works on iframes, because the event does not bubble up through the <iframe> tag's ancestors in the DOM.

Instead you can use the blur event to detect when your parent page is losing focus. This jQuery plugin is designed to track clicks on iframes : https://github.com/finalclap/iframeTracker-jquery

It's very easy to use, simply select your iframe with a selector, and supply a callback function (will be fired when the iframe is clicked) :

jQuery(document).ready(function($){
    $('.iframe_wrap iframe').iframeTracker({
        blurCallback: function(){
            // Do something when iframe is clicked (like firing an XHR request)
        }
    });
});
查看更多
混吃等死
3楼-- · 2019-07-25 01:36

You can't unless you're detecting the click from http://www.pbbgads.com/

查看更多
三岁会撩人
4楼-- · 2019-07-25 01:48

The code to alert is in the parent window and the ad I suppose is inside the iframe so it is not possible unless the parent page and iframe are in same domain.

查看更多
登录 后发表回答