Kumar
Kumar

Reputation: 874

URL of link from IFrame Javascript

This question may seen before. But in my scenario I didn't get the success. I have local HTML file loading in Iframe with sample external Link.

        <a href="http://www.boutell.com/">sample.com</a>

Code:

    <iframe id="iframe_Id" src="sample.html" 
style="background-color:white; height:100%; width:100%;" onload="Load()"; ></iframe>

    function Load() {
alert("loaded");
    var linkchange = document.getElementById("iframe_Id").contentWindow.location;
alert(linkchange);
}

While click on the external link I need the url value of particular anchor tag.

Edit: I know because of security policy we can't get URL when it is different domain. But I need the value from my local HTML page(the Link URL What I Clicked ). I didn't tried in this case

Any help is needed regarding this.

Upvotes: 0

Views: 3488

Answers (2)

Smeegs
Smeegs

Reputation: 9224

You can call a function in the parent window when you click on a link in the frame.

In the parent html you need to add a function to handle the call. Something like

function iframeLinkClicked(url) {
     //do stuff
}

Then in the child window add a function to handle the click event of a hyperlink.

function linkClicked(hyperLink) {
    parent.iframeLinkClicked(hyperLink.href);
}

You need to add this to all hyperlinks

<a href="http://www.google.com" onclick="linkClicked(this);">google</a>

Now, when you click on a link, it will alert the parent window.

Edit: alternative to adding "onclick" to every hyperlink.

You can add the event to the frame elements when the frame is loaded, if the frame html is in the same domain.

This is the complete script in the parent page.

<script type="text/javascript">

    function iframeLinkClicked(url) {
        alert(url);
    }
    function Load(iframe) {
        iframe.onload = null;
        try {
            var a = document.frames['iframe_Id'].document.getElementsByTagName('a');
            for (var i = 0; i < a.length; i++) {
                a[i].onclick = function () {
                    parent.iframeLinkClicked(this.href);
                    return false;
                };
            }
        } catch (e) {

        }

    }
</script>

This will replace your current Load() function. So the iframe still needs to have the load property set.

There is nothing to add to the child pages anymore. It's all done here.

<iframe id="iframe_Id" src="sample.html" 
style="background-color:white; height:100%; width:100%;" onload="Load(this);" ></iframe>

Upvotes: 2

aksu
aksu

Reputation: 5235

have a look at this:

var a = document.frames['iframe_Id'].document.getElementsByTagName('a');

for(i=0; i<a.length; i++) { 
  a[i].onclick = function() { 
    document.getElementById("iframe_Id").src = this.href;
    // and so on whatever you want to do
  }
}

Upvotes: 1

Related Questions