2012-01-17 30 views
3

是否可以檢索iframe頁面上的所有href元素?獲取iframe中的所有鏈接並添加空白目標屬性

這意味着,我有一個網頁是iframing來自不同網站的頁面。我在iframe中顯示的內容包含許多鏈接(href標籤)。

是否可以將BLANK的TARGET屬性添加到iframe中的所有鏈接?鏈接被埋在許多div和表格中,所以我需要能夠遞歸地在許多嵌套的表格/ div中添加屬性。

編輯: 新增截圖顯示需要被移除多餘的字符:

enter image description here

回答

4

如果iframe src在同一個域中,您可以通過使用document.getElementById(「frameID」)。文檔並對其進行操作來輕鬆訪問它。

如果它是你可以考慮的iframe鏈接到一個腳本在自己的域名,並且使該腳本從遠程域下載數據,並打印出來:)

myHTMLpage.html

不同的域
<html> 
    <head> 
    <title></title> 
     <script src="jquery-1.7.1.min.js" type="text/javascript"></script> 
    <script type="text/javascript"> 
     $(document).ready(function() { 
      $("#ifr").load(function() { 
       var ifr = document.getElementById("ifr") 
       var anchors = ifr.contentDocument.getElementsByTagName("a"); 
       for (var i in anchors) { 
        anchors[i].setAttribute("target", "_blank"); 
       } 
      }); 
     }); 
    </script> 
    </head> 
    <body> 
     <iframe src="myOwnSite.aspx" width="900px" height="600px" id="ifr" ></iframe> 
    </body> 
</html> 

myOwnSite.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MyOwnSite.aspx.cs" Inherits="MyOwnSite" %> 

個myOwnSite.aspx.cs

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Net; 


public partial class MyOwnSite : System.Web.UI.Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     if (!Page.IsPostBack) 
     { 
      Response.Write(new WebClient().DownloadString("http://theExternalSiteHere.com")); 
     } 
    } 
} 
+0

它位於不同的域。你能否詳細說明一下如何將iframe鏈接到我的域上的腳本,以便我可以下載數據並打印它?我完全不瞭解。謝謝 – obautista 2012-01-17 07:32:44

+1

您的頁面帶有iframe。 iframes src屬性指向您自己站點上的php或asp腳本。該腳本將下載應該在iframe和echo/response中的頁面,並將其寫入。現在,您在自己的域上擁有了正確的html。我在我的手機上,所以我不能給一個代碼示例。但如果它仍然沒有意義,我可以在半小時內爲你提供一個示例:) – f2lollpll 2012-01-17 07:41:09

+0

幾乎...它只是沒有將目標屬性添加到href標記。我試過你的代碼並使用jquery。 – obautista 2012-01-18 05:27:38

2

沒有,這是不可能的,如果iframe中的網站,其根據是不是在自己的網域描述似乎是這種情況。

1

嘗試增加<base target="_blank">你的iframe的head標籤內。

1

這是對我工作:

變種錨=的document.getElementById(id)的.contentWindow.document.getElementsByTagName( 「A」); (var i in anchors){ anchors [i] .target =「_blank」; //.setAttribute(「target」,「_blank」); }

我有IE8。 IE 6和IE 7的腳本可以不同。

相關問題