4

is it possible change or append hyperlink in a iframe?

Here is my code:

 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

    <script type="text/javascript">
    function changelinks(iframe){
      var as = iframe.contentDocument.getElementsByTagName('a');
      for(i=0;i<as.length;i++){
        as[i].setAttribute('href',"http://www.yahoo.com");
      }

    }

    </script>
    </head>

    <body>
    <iframe src="http://www.google.com" onload="changelinks(this)"></iframe>

My goal is when click on any link under iframe, destination url will be www.yahoo.com.

any suggestion is welcome. UPDATE I fetch website in iframe not located in my server.

Nand Lal
  • 682
  • 1
  • 11
  • 25

2 Answers2

2

Since you are using jquery.

function changelinks(iframe) {
    var frame = $( iframe ).get(0).contentDocument;

    $( 'a', frame ).click(function( event ) {
        event.preventDefault();
        location.href = 'http://yahoo.com';
    });
}

Or changing element attribute:

function changelinks(iframe) {
    var frame = $( iframe ).get(0).contentDocument;

    $( 'a', frame ).each(function() {
        $(this).attr('href', 'http://yahoo.com');
    });
}
jaapaurelio
  • 274
  • 4
  • 16
  • thanks for suggestion, still did not work. Note: I fetch website in iframe not located on my server. – Nand Lal Feb 22 '14 at 21:16
0

If the iframe url is an external url you run into an injection security issue...

see this: https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS this means you can only access DOM on your domain sites. you can do some php "proxy" hacks, where you can change the href attr but with simple javascirpt its not working.

(btw: there are some greasemonkey ways, but i think this is not an option for your site :))

regards Thomas

dschibait
  • 104
  • 4
  • If you show example code via php proxy hack, I'll be highly appreciate. – Nand Lal Feb 23 '14 at 09:35
  • You can get the site html by file_get_contents() (using the uri). now you need to replace the href value like this call: $pageHTML = preg_replace('#href=\"(.*)\"#isU', "href=\"" . $url . "\"", $pageHTML); (not tested) – dschibait Feb 23 '14 at 11:47