Jak zdobyć iframe src tytuł strony, a następnie ustawić główny tytuł stronyuzyskać tytuł strony iframe z javascript użyciu jquery
Odpowiedz
Jeżeli strona jest w iframe jest z tej samej domeny, co strony zawierającej, jest to niemożliwe.
Jeśli oni mają tę samą domenę, a następnie spróbuj wykonać następujące czynności:
document.title = document.getElementById("iframe").documentElement.title;
'contentDocument'. Z wyjątkiem IE6-7, gdzie musisz powrócić do niestandardowego 'contentWindow.document'. 'documentElement' to główny znacznik html; właściwość 'title' znajduje się w samym dokumencie HTMLDocument. – bobince
Udzielenie że iframe src i src dokument nadrzędny są takie same domeny:
dokument nadrzędny:
<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 zwraca null w przeglądarce Chrome. – msbg
Jeśli chcesz zrobić to za pomocą jQuery:
var title = $("#frame_id").contents().find("title").html();
$(document).find("title").html(title);
Można to zrobić tylko wtedy, gdy strony są w tej samej domenie, w przeciwnym razie nie ma sensu.
Jednym ze sposobów można udostępnić tytuł i lokalizację:
document.write('<iframe src="http://www.yourwebsite.com/home.html?title='+document.title+'&url='+window.location+'" frameborder="0" scrolling="no"></iframe>');
a następnie można odczytać parametry na stronie /home.html.
Można tego dokonać za pomocą detektorów zdarzeń na stronie. Nie jest to szczególnie eleganckie, ale przeglądarki, które wypróbowałem, obsługują go (więc IE9 +, Firefox, Chrome).
Na stronie głównej witryny należy dodać następujący skrypt:
function setPageTitle(event) {
var newPageTitle = event.data
// your code for setting the page title and anything else you're doing
}
addEventListener('message', setPageTitle, false);
w iframe, będziesz wtedy mieć następujący skrypt:
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
jest dostęp do stron w tej samej domenie. Jeśli nie oznacza to, że próbujesz wykonać Cross Site Scripting. Nadal możesz to zrobić, ale musisz ustawić domenę na stronie otwieranej w domenie iframe –
Domena jest inna – ebattulga