2014-02-22 129 views
2

是否可以在iframe中更改或附加超鏈接?IFrame中的HREF鏈接改變href值

這裏是我的代碼:

<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> 

我的目標是當點擊下iframe中的任何鏈接,目標網址將是www.yahoo.com。

任何建議是值得歡迎的。 UPDATE我在iframe中找不到位於我的服務器中的網站。

+0

這是因爲在iframe鏈接到雅虎的所有環節。 COM?如果是這樣,請參閱[這裏](http://stackoverflow.com/questions/1037839/how-to-force-link-from-iframe-to-be-opened-in-the-parent-window)。 – Wilf

+0

你不需要'setAttribute',你不可以只用'as [i] .href ='http:// www.yahoo.com''? – Cilan

+0

@Wilf我沒有發出父窗口或新的。 –

回答

1

由於您使用的是jQuery。

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

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

或改變元素屬性:

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

    $('a', frame).each(function() { 
     $(this).attr('href', 'http://yahoo.com'); 
    }); 
} 
+0

感謝您的建議,仍然沒有工作。注意:我在位於我的服務器上的iframe中訪問網站。 –

0

如果iframe網址是你碰到的注射安全問題的外部網址...

看到這一點:https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS 這意味着你可以只能訪問您的域名網站上的DOM。 你可以做一些PHP「代理」黑客,在那裏你可以改變href attr,但簡單的javascirpt它不工作。

(順便說一句:有一些Greasemonkey的方式,但我認爲這不是你的網站:)一個選項)

問候 托馬斯

+0

如果您通過php代理黑客展示示例代碼,我將非常感謝。 –

+0

您可以通過file_get_contents()(使用uri)獲取網站html。現在您需要像這樣調用替換href值:$ pageHTML = preg_replace('#href = \「(。*)\」#isU',「href = \」「。$ url。」\「」,$ pageHTML ); (未測試) – dschibait