关于 javascript:jQuery 从所有 iframe 中删除元素 | 珊瑚贝

jQuery remove element from all iframes


我有一个页面,其中包含 4 个 iframe。我想使用 jQuery(或纯 JavaScript)循环遍历所有这些 iframe(我不知道它们的 ID)和主框架并删除具有指定类名的元素。我将调用此函数从 Chrome 扩展程序中删除这些元素。

我该怎么做?感谢您的任何回答。


此解决方案的工作原理与 iFrame 相同。我创建了一个 PHP 脚本,可以从其他网站获取所有内容,最重要的是您可以轻松地将自定义 jQuery 应用于该外部内容。请参考以下脚本,该脚本可以从其他网站获取所有内容,然后您也可以应用您的自定义 jQuery/JS。此内容可以在任何地方、任何元素或任何页面内使用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
  <?php
   /*
    Use below function to display final HTML inside this div
   */

   //Display Frame
   echo displayFrame();
  ?>

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

      /* 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.navbardefault“).hide();

   “;

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

    //Return customized HTML
    return $html;
}


使用这些函数,并将 ‘.class-name’ 替换为你的类名(你可以使用任何 jQuery 选择器)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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();
    });
}

  • 顺便说一句,如果您的元素可能位于顶部框架中,您可能希望将”return element;”替换为”result.push(element);”并将”var result = [];”移动到函数的顶部。并且不要在 catch 中使用 return null。


使用 jQuery 你可以这样实现:

1
2
3
$(“iframe”).each(function() {
    $(this).contents().find(“element.classname”).remove();
});
  • 谢谢。但是我怎样才能从 iframe 上下文中调用它呢?


找到 iFrame 并使用 .contents():

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

用您的值替换 iframe、element 和 code。

可能的解决方案:

1
2
3
4
5
$(document).ready(function() {
    $.each(‘iframe’, function(k, v) {
        $(this).contents().find(‘div’).html(‘Hello, world!’);
    });
});

此外,这个问题已经在此处和此处得到解答。


类似这样的:

1
2
3
4
5
6
7
8
9
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

或使用香草js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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

编辑
添加了从 iframe 内部调用的可能性,但它们必须来自同一个域!!

  • 非常感谢,但此代码仅适用于从顶部框架调用它,而不是从 iframe 调用它。我忘了提及它 – 我想从顶部框架上下文或 iframe 上下文中删除这些元素。
  • 如果 iframe 来自不同的域,那么您需要使用 Porthole 之类的库来实现不同域之间的交叉通信。演示链接:sandbox.ternarylabs.com/porthole
  • 如果该框架来自同一个域,您可以使用 top.document
  • 基础起源相同。例如 – 主页在 admin.example.com 上,我正在从 sub.admin.example.com 加载 iframe。这不是跨域通信,对吧?
  • 看看这里:developer.mozilla.org/en-US/docs/Web/Security/… 你必须设置 document.domain


来源:https://www.codenong.com/26354717/

微信公众号
手机浏览(小程序)
0
分享到:
没有账号? 忘记密码?