2009-10-15 4 views
6

Jak zdobyć iframe src tytuł strony, a następnie ustawić główny tytuł stronyuzyskać tytuł strony iframe z javascript użyciu jquery

+1

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 –

+0

Domena jest inna – ebattulga

Odpowiedz

2

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; 
+1

'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

3

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> 
+1

iframe.contentWindow.document zwraca null w przeglądarce Chrome. – msbg

7

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.

1

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.

0

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