简体   繁体   中英

get iframe page title from javascript using jquery

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

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.

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>

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;

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM