我需要加載多個網站在iframes,同時也添加谷歌翻譯插件到每個頁面,以便他們可以被翻譯。這裏是我的插入部分的代碼:使用cURL檢索網站,並繞過相同的原點限制,插入javascript
<iframe onload="googleJS1(); googleJS2(); googleJS3();" class=iframe2 src=http://localhost:8888/mysitep></iframe>
<script>
function googleJS1() {
var iframe = document.getElementsByTagName('iframe')[0];
var doc = iframe.contentWindow.document;
var newScript = doc.createElement('div');
newScript.setAttribute("id", "google_translate_element");
var bodyClass = doc.getElementsByTagName('body')[0];
bodyClass.insertBefore(newScript, bodyClass.childNodes[0]);
}
function googleJS2() {
var iframe = document.getElementsByTagName('iframe')[0];
var doc = iframe.contentWindow.document;
var newScript = doc.createElement('script');
newScript.setAttribute("src", "http://translate.google.com/translate_a/element.js? cb=googleTranslateElementInit");
var bodyClass = doc.getElementsByTagName('head')[0];
bodyClass.insertBefore(newScript, bodyClass.childNodes[1]);
}
function googleJS3() {
var iframe = document.getElementsByTagName('iframe')[0];
var doc = iframe.contentWindow.document;
var newScript = doc.createElement('script');
newScript.setAttribute("src", "http://localhost:8888/mysite/google.js");
var bodyClass = doc.getElementsByTagName('head')[0];
bodyClass.insertBefore(newScript, bodyClass.childNodes[2]);
}
}
</script>
只要iframe目標URL位於同一臺服務器上,它就會工作。我閱讀繞過相同的原點約束我應該建立一個代理服務器,並通過代理傳遞所有的URL請求。所以我讀了cURL,並試圖作爲一個測試:
<?php
function get_data($url) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_USERAGENT, $userAgent);
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
curl_setopt($ch,CURLOPT_FOLLOWLOCATION,true);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$test = get_data("http://www.selfridges.com");
echo $test;
?>
基本的HTML元素被加載,但沒有CSS和圖像加載。此外,鏈接仍指向原始網址。我需要一些建議,關於如何將CSS,圖像和js從目標網址拖放到代理中,並從那裏加載網頁,使其看起來像來自相同的域和端口,並且通過傳遞相同的原始策略。我也需要鏈接以這種方式工作。
e.g:
main page - http://localhost:8888/proxy.php
links - http://localhost:8888/proxy.php/products/2012/shoes
任何其他方法或替代方案,也歡迎。
感謝
使用useragent模仿GoogleBot可能是一個壞主意。 –
這是_is_測試代碼 –
然後你不需要一個useragent - curl會自動發送一個。 –