This is my code:

<div id="main-content">
    <script>
        document.title = document.getElementById("main-content-iframe").contentDocument.title;
    </script>
    <iframe name="cstage" src="home.html" width="100%" height="100%" id="main-content-iframe" frameborder="0" onload="document.title=parent.frames['cframe'].document.title;">If you're seeing this message, it means IFrames are not supported; Please enable IFrames or upgrade to a compatible browser that supports IFrames.</iframe>
</div>

It's not working, what am I doing wrong?

有帮助吗?

解决方案

You need to check that the iframe is loaded.

<div id="main-content">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <iframe name="cstage" src="home.html" width="100%" height="100%" id="main-content-iframe" frameborder="0" onload="document.title=parent.frames['cframe'].document.title;">If you're seeing this message, it means IFrames are not supported; Please enable IFrames or upgrade to a compatible browser that supports IFrames.</iframe>
<script>
    $( "iframe" ).on('load',function() {
        document.title = document.getElementById("main-content-iframe").contentDocument.title;
    });
</script>

其他提示

You need to get the document.title of the page. When attempting to access elements inside of an iframe, you need to first get the iframe(which you did), then you can access any property of the document(the iframe) like you would normally.

General Answer

<iframe id="myFrame" src="https://www.example.com"></iframe>
<button onclick="getIframeTitle()">get iframe title</button>
function getIframeTitle() {
  // getting our iframe
  var iframe = document.getElementById("myFrame");
  // logging the iframe's title
  console.log(iframe.contentWindow.document.title);
}

Specific to your question

<div id="main-content">
    <script>
        document.title = document.getElementById("main-content-iframe").contentDocument.document.title;
    </script>
    <iframe name="cstage" src="home.html" width="100%" height="100%" id="main-content-iframe" frameborder="0" onload="document.title=parent.frames['cframe'].document.title;">If you're seeing this message, it means IFrames are not supported; Please enable IFrames or upgrade to a compatible browser that supports IFrames.</iframe>
</div>

See How TO - Get Iframe Elements for further reading.

Try code maybe can help you

HTML code:
<div id="main-content">   
    <iframe name="cstage" src="home.html" width="100%" height="100%" id="main-content-iframe" frameborder="0">If you're seeing this message, it means IFrames are not supported; Please enable IFrames or upgrade to a compatible browser that supports IFrames.</iframe>
</div> 

jQuery code:
alert($('#main-content-iframe').contents().find("title").text());

Note: Make sure home.html come from the same domain as your main page.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top