Ottieni i contenuti HTML di un altro frame su un altro dominio
-
20-08-2019 - |
Domanda
Ho letto che non puoi leggere l'HTML di un altro frame se quel frame risiede su un altro dominio. C'è un modo per farlo in Javascript? Mi rendo conto che questa limitazione è per motivi di sicurezza ma il mio uso è legittimo.
Saluti
Peter
Soluzione
Stiamo parlando di un iFrame qui? In tal caso, non potresti ottenere l'attributo src di iFrame (jQuery?) E avviare una richiesta Ajax che restituirebbe la pagina, o forse consegnare l'attributo src al tuo script (PHP / ASP qualunque) che utilizza CURL per raccogliere il informazioni che stai cercando?
Altri suggerimenti
Sì, puoi sicuramente leggere il contenuto del frame usando il proxy tra domini. In sostanza, è necessario creare uno script sul lato server che richiede l'URL src del frame in questione. Sul lato client, si richiede questo script anziché l'URL src (che si trova su un altro dominio e quindi soggetto a restrizioni di sicurezza all'interno del browser), passando l'URL src come parametro.
Script lato server
Di seguito è riportato un esempio con PHP che utilizza cURL.
<?php
$target = $_REQUEST['t'];
if (empty($target)) { die 'no url provided'; }
$useragent="Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.10) Gecko/2009042316 Firefox/3.0.10";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $target);
curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$res = curl_exec($ch);
curl_close($ch);
echo $res;
?>
Script lato client
Nella tua pagina, utilizza la seguente funzione JavaScript per restituire l'HTML del frame di destinazione
var URL = top.frames.(YOUR FRAME NAME HERE).location;
var xh = null;
if (window.XMLHttpRequest) {
xh = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xh = new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("Your browser does not support XMLHTTP.");
return false;
}
var ret = null;
xh.onreadystatechange = function() {
if (xh.readyState == 4 && xh.status == 200) {
// do whatever you want with the html here
ret = xh.responseText;
}
}
xh.open("GET", url, false);
xh.send(null);
Fammi sapere se questo funziona per te.