get iframe page title from javascript using jquery

2019-01-18 07:13发布

问题:

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

回答1:

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.



回答2:

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>


回答3:

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;


回答4:

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.



回答5:

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