草庐IT

关于 javascript:jQuery 从所有 iframe 中删除元素

codeneng 2023-03-28 原文

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.navbar-default").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);
});

用您的值替换 iframeelementcode

可能的解决方案:

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

有关关于 javascript:jQuery 从所有 iframe 中删除元素的更多相关文章

  1. ruby - 如何以所有可能的方式将字符串拆分为长度最多为 3 的连续子字符串? - 2

    我试图获取一个长度在1到10之间的字符串,并输出将字符串分解为大小为1、2或3的连续子字符串的所有可能方式。例如:输入:123456将整数分割成单个字符,然后继续查找组合。该代码将返回以下所有数组。[1,2,3,4,5,6][12,3,4,5,6][1,23,4,5,6][1,2,34,5,6][1,2,3,45,6][1,2,3,4,56][12,34,5,6][12,3,45,6][12,3,4,56][1,23,45,6][1,2,34,56][1,23,4,56][12,34,56][123,4,5,6][1,234,5,6][1,2,345,6][1,2,3,456][123

  2. ruby-on-rails - 如何从 format.xml 中删除 <hash></hash> - 2

    我有一个对象has_many应呈现为xml的子对象。这不是问题。我的问题是我创建了一个Hash包含此数据,就像解析器需要它一样。但是rails自动将整个文件包含在.........我需要摆脱type="array"和我该如何处理?我没有在文档中找到任何内容。 最佳答案 我遇到了同样的问题;这是我的XML:我在用这个:entries.to_xml将散列数据转换为XML,但这会将条目的数据包装到中所以我修改了:entries.to_xml(root:"Contacts")但这仍然将转换后的XML包装在“联系人”中,将我的XML代码修改为

  3. ruby - 我可以使用 Ruby 从 CSV 中删除列吗? - 2

    查看Ruby的CSV库的文档,我非常确定这是可能且简单的。我只需要使用Ruby删除CSV文件的前三列,但我没有成功运行它。 最佳答案 csv_table=CSV.read(file_path_in,:headers=>true)csv_table.delete("header_name")csv_table.to_csv#=>ThenewCSVinstringformat检查CSV::Table文档:http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV/Table.html

  4. ruby - 我可以使用 aws-sdk-ruby 在 AWS S3 上使用事务性文件删除/上传吗? - 2

    我发现ActiveRecord::Base.transaction在复杂方法中非常有效。我想知道是否可以在如下事务中从AWSS3上传/删除文件:S3Object.transactiondo#writeintofiles#raiseanexceptionend引发异常后,每个操作都应在S3上回滚。S3Object这可能吗?? 最佳答案 虽然S3API具有批量删除功能,但它不支持事务,因为每个删除操作都可以独立于其他操作成功/失败。该API不提供任何批量上传功能(通过PUT或POST),因此每个上传操作都是通过一个独立的API调用完成的

  5. ruby-on-rails - 跳过状态机方法的所有验证 - 2

    当我的预订模型通过rake任务在状态机上转换时,我试图找出如何跳过对ActiveRecord对象的特定实例的验证。我想在reservation.close时跳过所有验证!叫做。希望调用reservation.close!(:validate=>false)之类的东西。仅供引用,我们正在使用https://github.com/pluginaweek/state_machine用于状态机。这是我的预订模型的示例。classReservation["requested","negotiating","approved"])}state_machine:initial=>'requested

  6. ruby - Nokogiri 剥离所有属性 - 2

    我有这个html标记:我想得到这个:我如何使用Nokogiri做到这一点? 最佳答案 require'nokogiri'doc=Nokogiri::HTML('')您可以通过xpath删除所有属性:doc.xpath('//@*').remove或者,如果您需要做一些更复杂的事情,有时使用以下方法遍历所有元素会更容易:doc.traversedo|node|node.keys.eachdo|attribute|node.deleteattributeendend 关于ruby-Nokog

  7. ruby - 获取模块中定义的所有常量的值 - 2

    我想获取模块中定义的所有常量的值:moduleLettersA='apple'.freezeB='boy'.freezeendconstants给了我常量的名字:Letters.constants(false)#=>[:A,:B]如何获取它们的值的数组,即["apple","boy"]? 最佳答案 为了做到这一点,请使用mapLetters.constants(false).map&Letters.method(:const_get)这将返回["a","b"]第二种方式:Letters.constants(false).map{|c

  8. jquery - 我的 jquery AJAX POST 请求无需发送 Authenticity Token (Rails) - 2

    rails中是否有任何规定允许站点的所有AJAXPOST请求在没有authenticity_token的情况下通过?我有一个调用Controller方法的JqueryPOSTajax调用,但我没有在其中放置任何真实性代码,但调用成功。我的ApplicationController确实有'request_forgery_protection'并且我已经改变了config.action_controller.consider_all_requests_local在我的environments/development.rb中为false我还搜索了我的代码以确保我没有重载ajaxSend来发送

  9. ruby - 如何安全地删除文件? - 2

    在Ruby中是否有Gem或安全删除文件的方法?我想避免系统上可能不存在的外部程序。“安全删除”指的是覆盖文件内容。 最佳答案 如果您使用的是*nix,一个很好的方法是使用exec/open3/open4调用shred:`shred-fxuz#{filename}`http://www.gnu.org/s/coreutils/manual/html_node/shred-invocation.html检查这个类似的帖子:Writingafileshredderinpythonorruby?

  10. ruby - 在哈希的键数组中追加元素 - 2

    查看我的Ruby代码:h=Hash.new([])h[0]=:word1h[1]=h[1]输出是:Hash={0=>:word1,1=>[:word2,:word3],2=>[:word2,:word3]}我希望有Hash={0=>:word1,1=>[:word2],2=>[:word3]}为什么要附加第二个哈希元素(数组)?如何将新数组元素附加到第三个哈希元素? 最佳答案 如果您提供单个值作为Hash.new的参数(例如Hash.new([]),完全相同的对象将用作每个缺失键的默认值。这就是您所拥有的,那是你不想要的。您可以改用

随机推荐