get iframe page title from javascript using jquery

前端 未结 5 991
再見小時候
再見小時候 2020-12-09 22:33

How to get iframe src page title and then set main page title

相关标签:
5条回答
  • 2020-12-09 23:19

    Unless the webpage is in the iframe is from the same domain as the containing page, it is impossible.

    If they do have the same domain, then try the following:

    document.title = document.getElementById("iframe").documentElement.title;
    
    0 讨论(0)
  • 2020-12-09 23:21

    One way you can share title and location:

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

    and then you can read the parameters on home.html page.

    0 讨论(0)
  • 2020-12-09 23:24

    If you want to do it using jQuery:

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

    You can do it only when pages are on the same domain, otherwise it's useless.

    0 讨论(0)
  • 2020-12-09 23:28

    This can be done using event listeners on the page. It's not particularly elegant, but the browsers I have tried it with support it (so IE9+, Firefox, Chrome).

    In your main site page add the following 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);
    

    In the iFrame, you'll then need to have the following script:

    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
    
    0 讨论(0)
  • 2020-12-09 23:31

    Granting that iframes src and the parent document src are the same domain:

    Parent document:

    <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>
    
    0 讨论(0)
提交回复
热议问题