获取 iframe 内的所有链接并添加空白目标属性

oba*_*sta 3 html javascript jquery

是否可以检索作为 iframe 的页面上的所有 href 元素?

意思是,我有一个页面正在对来自不同站点的页面进行 iframe。我在 iframe 中显示的内容包含许多链接(href 标签)。

是否可以向 iframe 内的所有链接添加 BLANK 的 TARGET 属性?链接隐藏在许多 div 和表中,因此我需要能够在许多嵌套表/div 中递归添加属性。

编辑:添加屏幕截图以显示需要删除的额外字符:

在此处输入图片说明

f2l*_*pll 5

如果 iframe src 位于同一个域中,您可以使用 document.getElementById("frameID").document 轻松访问它并对其进行操作。

如果是不同的域,您可以考虑将 iframe 链接到您自己域中的脚本,并使该脚本从远程域下载数据并打印出来:)

我的HTML页面.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>
Run Code Online (Sandbox Code Playgroud)

我的网站.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MyOwnSite.aspx.cs" Inherits="MyOwnSite" %>
Run Code Online (Sandbox Code Playgroud)

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"));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)