1

I have a page, that contains 4 iframes. I want to use jQuery (or pure JavaScript) to loop through all these iframes (I don't know their IDs) and main frame and remove element with specified classname. I will call this function to remove these elements from Chrome extension.

How can I do this? Thanks for any answers.

Jakub Dibala
  • 95
  • 2
  • 8

5 Answers5

0

something like this:

var 
  i, len,
  target_class = 'class_name',
  $iframes = $( 'iframe', top.document );         // <-- add top.document

for ( i = 0, len = $iframes.length; i < len; ++i ) {
  $iframes.eq( i ).contents().find( '.'+ target_class ).remove();
}
$( '.'+ target_class, top.document ).remove();    // <-- add top.document

or with vanilla js:

var
  i, len,
  target_class = 'class_name',
  iframes = top.document.getElementsByTagName( 'iframe' ), // <-- add top.document

  removeByClass = function ( doc, class_name ) {
    var i, len, el, 
      toRemoves = doc.getElementsByClassName( class_name );

    for ( i = 0, len = toRemoves.length; i < len; ++i ) {
      el = toRemoves[ i ];
      if ( el.parentNode ) {
        el.parentNode.removeChild( el );
      }
    }
  };

for ( i = 0, len = iframes.length; i < len; ++i ) {
  removeByClass( iframes[ i ].contentDocument, target_class );
}

removeByClass( top.document, target_class );    // <-- add top.document

EDIT Added the possibility to call from inside the iframes, but they MUST be from the same domain!!

TheGr8_Nik
  • 3,080
  • 4
  • 18
  • 33
  • Many thanks, but this code works only for calling it from top frame, but not from iframe. I forgot to mention it - I want to remove these elements from top frame context or from iframe context. – Jakub Dibala Oct 14 '14 at 07:23
  • If the iframes are from different domains, then you need to use libraries like Porthole for cross-communication between different domains. Demo link: http://sandbox.ternarylabs.com/porthole/ – Manoj Namodurai Oct 14 '14 at 07:29
  • if that frame is from the same domain you can use top.document – TheGr8_Nik Oct 14 '14 at 07:33
  • Base origins are the same. For example - main page is on admin.example.com and I'm loading iframes from sub.admin.example.com. It isn't cross-domain communication, right? – Jakub Dibala Oct 14 '14 at 07:33
  • give a look here: https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy you have to set the `document.domain` – TheGr8_Nik Oct 14 '14 at 07:43
0

Find the iFrame and use .contents():

$(document).ready(function() {
    $(iframe).contents().find(element).html(code);
});

Substitute iframe, element and code with your values.

Potential solution:

$(document).ready(function() {
    $.each('iframe', function(k, v) {
        $(this).contents().find('div').html('Hello, world!');
    });
});

Also, this question has been answered before here and here.

Community
  • 1
  • 1
martynas
  • 12,120
  • 3
  • 55
  • 60
0

With jQuery you could achieve that like this:

$("iframe").each(function() {
    $(this).contents().find("element.classname").remove();
});
pimmey
  • 461
  • 2
  • 7
0

Use these functions, and replace '.class-name' with your class name (you can use any jQuery selector).

var getIFrameDocument = function(iframe) {
    var doc;
    try {
        if ((typeof InstallTrigger !== 'undefined') && (iframe.contentDocument)) { // Firefox, Opera
            doc = iframe.contentDocument;
        } else if (iframe.contentWindow) { // Internet Explorer
            doc = iframe.contentWindow.document;
        } else if (iframe.document) { // Others?
            doc = iframe.document;
        }
    } catch(e) {
    }

    return doc;
};

var findElementRecursively = function(selector, doc) {
    try { /* Helps prevent errors like "Permission denied to access property 'jquery'" */
        var element = jQuery(selector, doc);
    } catch (e) {
        return null;
    }

    if (element.length !== 0) {
        return element;
    }

    try {
        if (doc && doc.location === 'about:blank') {
            return null;
        }
    } catch (e) {
    }

    try { /* Helps prevent errors like "Permission denied to access property 'jquery'" */
        var iframes = jQuery("iframe", doc);
    } catch (e) {
        return null;
    }

    var result = [];
    for (var i = 0; i < iframes.length; i++) {
        var iframeDoc = getIFrameDocument(iframes[i]);

        if (!(typeof(iframeDoc) === 'undefined')) {
            element = findElementRecursively(selector, iframeDoc);
            if (!(element === null)) {
                for (var j = 0; j < element.length; j++) {
                    result.push(element[j]);
                }
            }
        }
    }

    if (result.length > 0) {
        return jQuery(result);
    } else {
        return null;
    }
};

var element = findElementRecursively('.class-name', document);
if ((!(element === null)) && (element.length > 0)) {
    // element.remove(); // I'm not sure if this works.
    element.each(function() {
        jQuery(this).remove();
    });
}
Uri
  • 2,992
  • 8
  • 43
  • 86
  • By the way, if your element may be in the top frame, you might want to replace "`return element;`" with "`result.push(element);`" and move "`var result = [];`" to the top of the function. And don't `return null` in the `catch`. – Uri Oct 14 '14 at 08:00
0

This solution works same as iFrame. I have created a PHP script that can get all the contents from the other website, and most important part is you can easily apply your custom jQuery to that external content. Please refer to the following script that can get all the contents from the other website and then you can apply your cusom jQuery/JS as well. This content can be used anywhere, inside any element or any page.

<div id='myframe'>

  <?php 
   /* 
    Use below function to display final HTML inside this div
   */

   //Display Frame
   echo displayFrame(); 
  ?>

</div>

<?php

/* 
    Function to display frame from another domain 
*/

function displayFrame()
{
    $webUrl = 'http://[external-web-domain.com]/';

    //Get HTML from the URL
    $content = file_get_contents($webUrl);

    //Add custom JS to returned HTML content
    $customJS = "
    <script>

      /* Here I am writing a sample jQuery to hide the navigation menu
         You can write your own jQuery for this content
      */
      //Hide Navigation bar
      jQuery(\".navbar.navbar-default\").hide();

    </script>";

    //Append Custom JS with HTML
    $html = $content . $customJS;

    //Return customized HTML
    return $html;
}
Ahsan Horani
  • 239
  • 2
  • 13