【问题标题】:get iframe page title from javascript using jquery使用 jquery 从 javascript 获取 iframe 页面标题
【发布时间】:2010-12-06 22:45:29
【问题描述】:

如何获取 iframe src 页面标题,然后设置主页标题

【问题讨论】:

  • 页面是否在同一个域中。如果不是,则意味着您尝试执行跨站点脚本。您仍然可以这样做,但您需要在 iframe 中打开的页面中设置域

标签: javascript jquery html iframe


【解决方案1】:

如果你想使用 jQuery:

var title = $("#frame_id").contents().find("title").html();
$(document).find("title").html(title);

只有页面在同一个域时才可以这样做,否则没用。

【讨论】:

    【解决方案2】:

    授予 iframe src 和父文档 src 是同一个域:

    父文档:

    <html>
    <head><title>Parent</title>
    <body>
       <iframe id="f" src="someurl.html"></iframe>
       <script>
           //if the parent should set the title, here it is
           document.title = document.getElementById('f').contentWindow.document.title;
       </script>
    </body>
    </html>
    

    someurl.html:

    <html>
    <head><title>Child</title>
    <body>
      <script>
           //if the child wants to set the parent title, here it is
           parent.document.title = document.title;
           //or top.document.title = document.title;
    
      </script>
    </body> 
    </html>
    

    【讨论】:

    • iframe.contentWindow.document 在 Chrome 中返回 null。
    【解决方案3】:

    除非网页在 iframe 中与包含页面来自同一域,否则这是不可能的。

    如果他们确实具有相同的域,请尝试以下操作:

    document.title = document.getElementById("iframe").documentElement.title;
    

    【讨论】:

    • contentDocument。除了在 IE6-7 中,您必须退回到非标准的contentWindow.documentdocumentElement 是根 html 标记; title 属性位于 HTMLDocument 本身。
    【解决方案4】:

    您可以共享标题和位置的一种方式:

    document.write('<iframe src="http://www.yourwebsite.com/home.html?title='+document.title+'&url='+window.location+'" frameborder="0" scrolling="no"></iframe>');
    

    然后就可以在home.html页面读取参数了。

    【讨论】:

      【解决方案5】:

      这可以使用页面上的事件侦听器来完成。它不是特别优雅,但我尝试过的浏览器都支持它(例如 IE9+、Firefox、Chrome)。

      在您的主站点页面中添加以下 javascript:

      function setPageTitle(event) {
          var newPageTitle = event.data
          // your code for setting the page title and anything else you're doing
      }
      addEventListener('message', setPageTitle, false);
      

      在 iFrame 中,您需要拥有以下脚本:

      var targetOrigin = "http://your.domain.com"; // needed to let the browser think the message came from your actual domain
      parent.postMessage("New page title", targetOrigin); // this will trigger the message listener in the parent window
      

      【讨论】:

      • 更多浏览器支持使用: if (window.addEventListener) { window.addEventListener("message", listener); } else { // IE8 window.attachEvent("onmessage", listener); }
      猜你喜欢
      • 2019-03-06
      • 1970-01-01
      • 2011-08-05
      • 1970-01-01
      • 2013-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-06
      相关资源
      最近更新 更多