How to use the preventDefault function in a click event inside an iframe?

2

I manipulate the iframe's DOM as follows: ( link )

$('iframe').contents().find('a').função();

We usually use the preventDefault function like this:

$( "a" ).click(function( event ) {
  event.preventDefault();
});

Doubt:

How do I use the preventDefault() function in a click event for all the $('a') link tags within the iframe? Basically I need no links to be clicked inside the iframe.

I've tested it this way, but it does not work:

$('iframe').contents().find('a').click(function (e) { 
   e.preventDefault();
});
    
asked by anonymous 13.12.2014 / 06:10

3 answers

0

In order to resolve the problem, if the iFrame is in the same domain as the parent page, you must add the .ready() event to the iframe, since it must be fully loaded before applying the .click() event. It looks like this:

$(document).ready(function() {
    $("#id_do_iframe").ready(function () {
        $('#id_do_iframe').contents().find('a').click(function (e) { 
             e.preventDefault();
        });
    });
});
    
13.12.2014 / 20:56
2

If the iFrame is in a different domain then your solution with jQuery will not work because it violates a security rule and browsers do not allow it.

One solution I see is to block the iFrame with a div on your page, which stands above the iFrame, and thus "cap" the interaction with the iFrame.

Another option, even better (for modern browsers) is the renan solution with pointer events.

Example:

(note that I gave a border in the blocking div just to be visible)

#bloqueador {
    position: absolute;
    top: 0px;
    border: 2px solid #ccf;
    height: 300px;
    width: 300px;
}
<iframe src="http://www.cnn.com"frameborder="0"></iframe>
<div id="bloqueador"></div>
    
13.12.2014 / 08:44
2

One solution only using CSS would be to use the pointer-events property on <iframe> . Just be aware of which browsers support .

iframe {
  pointer-events: none
}
<iframe src="http://tympanus.net/codrops/"frameborder="0"></iframe>

MDN

    
13.12.2014 / 09:33