Javascript – How to open links in an iframe with target=“_blank” in the same iframe

iframejavascriptPHP

I want to Open links with target=“_blank” and an iframe in the same iframe.
I tried the code below, but it didn't work. Php solutions are welcome!

<script src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js" type="text/javascript"></script>


<iframe src="http://www.htmlcodetutorial.com/linking/_A_TARGET_95y98y108y97y110y107y.html" height="100%" width="100%" ></iframe>

<script>
$('iframe a[target="_blank"]').live('click',function(e){
e.preventDefault(); //stops it opening in a new window
var url = $(this).attr('href');
$('iframe').load(url);
});

</script> 

Best Answer

Have you tried simply changing the target attribute?

$('iframe a[target="_blank"]').each(function () {
    $(this).attr('target', '_self');
});

Also, Zain Shaikh is quite correct. If the source of the iframe is loaded from a different domain, you will not be able to do this from JavaScript.

You can still do this server-side, but that's going to be dependent on which language you use.

As far as a native JavaScript solution:

function replaceWithSelf () {
    var iframes = document.getElementsByTagName('iframe');
    var i = 0;
    var j = 0;
    var anchors;
    for (i = 0; i < iframes.length; i += 1) {
        anchors = iframes[i].getElementsByTagName('a');
        for (j = 0; j < anchors.length; j += 1) {
            if (anchors[j].getAttribute('target') === '_blank') {
                anchors[j].setAttribute('target', '_self');
            }
        }
    }
}

I tested the relevant portion at http://www.htmlcodetutorial.com/linking/_A_TARGET_95y98y108y97y110y107y.html (as described in your question). The test code used was:

var anchors = document.getElementsByTagName('a');
for (var j = 0; j < anchors.length; j += 1) {
    if (anchors[j].getAttribute('target') === '_blank') {
        anchors[j].setAttribute('target', '_self');
    }
}

which I ran in the console (Google Chrome). Code worked as intended.

To re-iterate, if the source of the iframe is loaded from a different domain, you will not be able to do this from JavaScript.

To put it another way, unless the domain you are running YOUR code on is also http://www.htmlcodetutorial.com, you will NOT be able to do this in JavaScript.