Make links in iframe from a different domain open

2019-02-21 06:49发布

问题:

This question is for advanced javascript programmers! -Sorry for my bad english :(

We have the following scenario:

--- Site A gives me a script.

--- I put the script on site B (on index.html)

--- The script generate an iframe, that contains a link(< a >)

Result => Site B contains an ifame with a link in it ,from site A

All i want to do is "To open the link in new tab" :D

I can do this by adding with javascript attribute target="_blank".. BUT i CANT select the link() with javascript because the iframe is from another site. For security reasons browsers dont let you to access the content of an iframe if is not from your site.

I am loking for some sort of a hack... I was thinking if playing with events will help me ?

Like catching the event of link click, than stop the event and than fire new event to open link in new tab.

Or catch the leftclick event, stop event, fire right click event than, from the cotext menu select "open link in new tab" (all of this happens when user leftclick the link)

Any suggestions are welcome, i need to look this problem from a different perspective...

回答1:

You could use a proxy. Here is the code that I use:

get.php

<?php
  // if no URL is submitted, exit
  if(!isset($_REQUEST['url'])){echo 'You did not specify a URL'; exit();}
  $url = $_REQUEST['url'];
  // instanciate the cURL connection
  $ch = curl_init();
  // set the URL
  curl_setopt($ch, CURLOPT_URL, $url);
  // this will allow you to print the content on your page
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  // this is to get the content type (for images for example)
  curl_setopt($ch,CURLOPT_HEADER,true);
  $res = curl_exec($ch);
  // seperate the headers and content
  list($headers,$content) = explode("\r\n\r\n",$res,2);
  // set the content type
  header('Content-type: '.curl_getinfo($ch,CURLINFO_CONTENT_TYPE));
  // display the results
  echo $content;
  // close the connection
  curl_close($ch);
?>

You can use it by passing it the link:

http://yourdomain.com/get.php?url=http%3A%2F%2Fotherdomain.com%2Fpage.html%0D%0A

As you can see, the URL that is passed should be urlEncoded. Also note that any relative paths in the other page will fail to load (you could improve this by replacing any relative path by an absolute one).