Skip to content Skip to sidebar Skip to footer

Get All Links Inside Iframe And Add Blank Target Attribute

Is it possible to retrieve all href elements on a page that is an iframe? Meaning, I have a page that is iframing a page from different site. What I am showing in the iframe con

Solution 1:

If the iframe src it's on the same domain you can easily access it by using document.getElementById("frameID").document and manipulate that.

If it's a different domain you may consider link the iframe to a script in your own domain, and make that script download the data from the remote domain and print out:)

myHTMLpage.html

<html><head><title></title><scriptsrc="jquery-1.7.1.min.js"type="text/javascript"></script><scripttype="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><iframesrc="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;


publicpartialclassMyOwnSite : System.Web.UI.Page
{
    protectedvoidPage_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            Response.Write(new WebClient().DownloadString("http://theExternalSiteHere.com"));
        }
    }
}

Solution 2:

No, this is not possible if the site inside the iframe is not on your domain which according to your description seems to be the case.

Solution 3:

Try adding <base target="_blank"> inside the head tag of your iframe.

Solution 4:

This is what worked for me:

var anchors= document.getElementById(id).contentWindow.document.getElementsByTagName("a"); for (var i in anchors) { anchors[i].target = "_blank"; //.setAttribute("target", "_blank"); }

I have IE8. The script for IE 6 and IE 7 can be different.

Post a Comment for "Get All Links Inside Iframe And Add Blank Target Attribute"