jQuery / JavaScript: dostęp do zawartości iframe

Chciałbym manipulować HTML wewnątrz ramki iframe za pomocą jQuery.

Myślałem, że będę w stanie to zrobić, ustawiając kontekst funkcji jQuery jako dokument iframe, coś w stylu:

$(function(){ //document ready
    $('some selector', frames['nameOfMyIframe'].document).doStuff()
});

To jednak nie działa. Trochę inspekcji pokazuje mi, że zmienne w frames['nameOfMyIframe']undefined, chyba że poczekam chwilę na załadowanie iframe. Jednakże, gdy ramka iframe ładuje zmienne nie są dostępne(dostaję błędy typu permission denied).

Czy ktoś wiesz, jak to obejść?
Author: Druzion, 2008-12-13

11 answers

Myślę, że to, co robisz, podlega Tej Samej polityce pochodzenia . To powinien być powód, dla którego pojawiają się błędy typu permission denied type .

 355
Author: Onur Bebin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-12-13 14:14:03

Jeśli {[1] } pochodzi z tej samej dziedziny, elementy są łatwo dostępne jako

$("#iFrame").contents().find("#someDiv").removeClass("hidden");

Bibliografia

 938
Author: Yasir Laghari,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-30 17:51:05
$(document).ready(function(){
    $('#frameID').load(function(){
        $('#frameID').contents().find('body').html('Hey, i`ve changed content of <body>! Yay!!!');
    });
});
 78
Author: davryusha,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-04-02 18:27:46

Jeśli iframe src jest z innej domeny, nadal możesz to zrobić. Musisz odczytać zewnętrzną stronę w PHP i echo jej z Twojej domeny. TAK:

Iframe_page.php

<?php
    $URL = "http://external.com"

    $domain = file_get_contents($URL)

    echo $domain
?>

Wtedy coś takiego:

Display_page.html

<html>
<head>
  <title>Test</title>
 </head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>

<script>

$(document).ready(function(){   
    cleanit = setInterval ( "cleaning()", 500 );
});

function cleaning(){
    if($('#frametest').contents().find('.selector').html() == "somthing"){
        clearInterval(cleanit);
        $('#selector').contents().find('.Link').html('ideate tech');
    }
}

</script>

<body>
<iframe name="frametest" id="frametest" src="http://yourdomain.com/iframe_page.php" ></iframe>
</body>
</html>

Powyższe jest przykładem jak edytować zewnętrzną stronę przez ramkę iframe bez odmowy dostępu itp...

 41
Author: basysmith,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-06-27 10:15:18

Użyj

iframe.contentWindow.document

Zamiast

iframe.contentDocument
 30
Author: user,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-30 19:15:50

I find this way cleaner:

var $iframe = $("#iframeID").contents();
$iframe.find('selector');
 28
Author: zupa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-06 12:00:29

Musisz dołączyć Zdarzenie do obsługi onload ramki iframe i wykonać js, aby upewnić się, że ramka iframe zakończyła Ładowanie przed uzyskaniem dostępu do niego.

$().ready(function () {
    $("#iframeID").ready(function () { //The function below executes once the iframe has finished loading
        $('some selector', frames['nameOfMyIframe'].document).doStuff();
    });
};

Powyższe rozwiązanie rozwiąże problem "jeszcze nie załadowany", ale jeśli chodzi o uprawnienia, jeśli ładujesz stronę w ramce iframe, która pochodzi z innej domeny, nie będziesz mógł uzyskać do niej dostępu z powodu ograniczeń bezpieczeństwa.

 25
Author: Andreas Grech,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-12-13 08:22:16

Możesz użyć window.postMessage do wywołania funkcji między stroną a jego ramką iframe (cross domain lub nie).

Dokumentacja

Strona.html

<!DOCTYPE html>
<html>
<head>
    <title>Page with an iframe</title>
    <meta charset="UTF-8" />
    <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
    <script>
    var Page = {
        id:'page',
        variable:'This is the page.'
    };

    $(window).on('message', function(e) {
        var event = e.originalEvent;
        if(window.console) {
            console.log(event);
        }
        alert(event.origin + '\n' + event.data);
    });
    function iframeReady(iframe) {
        if(iframe.contentWindow.postMessage) {
            iframe.contentWindow.postMessage('Hello ' + Page.id, '*');
        }
    }
    </script>
</head>
<body>
    <h1>Page with an iframe</h1>
    <iframe src="iframe.html" onload="iframeReady(this);"></iframe>
</body>
</html>

Iframe.html

<!DOCTYPE html>
<html>
<head>
    <title>iframe</title>
    <meta charset="UTF-8" />
    <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
    <script>
    var Page = {
        id:'iframe',
        variable:'The iframe.'
    };

    $(window).on('message', function(e) {
        var event = e.originalEvent;
        if(window.console) {
            console.log(event);
        }
        alert(event.origin + '\n' + event.data);
    });
    $(window).on('load', function() {
        if(window.parent.postMessage) {
            window.parent.postMessage('Hello ' + Page.id, '*');
        }
    });
    </script>
</head>
<body>
    <h1>iframe</h1>
    <p>It's the iframe.</p>
</body>
</html>
 19
Author: B.Asselin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-26 15:38:04

Wolę użyć innego wariantu dostępu. Od rodzica możesz mieć dostęp do zmiennej w ramce iFrame potomka. $ jest również zmienną i możesz otrzymać dostęp do jej samego wywołania window.iframe_id.$

Na przykład, window.view.$('div').hide() - Ukryj wszystkie div w iframe o id 'view'

Ale nie dziala w FF. Dla lepszej kompatybilności należy użyć

$('#iframe_id')[0].contentWindow.$

 4
Author: Evgeny Karpov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-29 22:37:11

Tworzę przykładowy kod . Teraz możesz łatwo zrozumieć z innej domeny, do której nie masz dostępu zawartość iframe .. W tej samej domenie możemy uzyskać dostęp do zawartości iframe

Udostępniam ci Mój kod, proszę uruchom ten kod sprawdź konsolę . Drukuję obraz src na konsoli. Istnieją cztery ramki iframe, dwa iFrame pochodzące z tej samej domeny i pozostałe dwa z innej domeny (strony trzeciej) .Można zobaczyć dwa obrazy src( https://www.google.com/logos/doodles/2015/googles-new-logo-5078286822539264.3-hp2x.gif

I

Https://www.google.com/logos/doodles/2015/arbor-day-2015-brazil-5154560611975168-hp2x.gif ) w konsoli, a także może zobaczyć dwa błędy uprawnień( 2 Error: Permission denied to access property 'document'

...irstChild)}, contents: function (a) {return m. nodename (a,"iframe")?a. contentDocument...

), który pochodzi z zewnętrznego iframe.

<body id="page-top" data-spy="scroll" data-target=".navbar-fixed-top">
<p>iframe from same domain</p>
  <iframe frameborder="0" scrolling="no" width="500" height="500"
   src="iframe.html" name="imgbox" class="iView">

</iframe>
<p>iframe from same domain</p>
<iframe frameborder="0" scrolling="no" width="500" height="500"
   src="iframe2.html" name="imgbox" class="iView1">

</iframe>
<p>iframe from different  domain</p>
 <iframe frameborder="0" scrolling="no" width="500" height="500"
   src="https://www.google.com/logos/doodles/2015/googles-new-logo-5078286822539264.3-hp2x.gif" name="imgbox" class="iView2">

</iframe>

<p>iframe from different  domain</p>
 <iframe frameborder="0" scrolling="no" width="500" height="500"
   src="http://d1rmo5dfr7fx8e.cloudfront.net/" name="imgbox" class="iView3">

</iframe>

<script type='text/javascript'>


$(document).ready(function(){
    setTimeout(function(){


        var src = $('.iView').contents().find(".shrinkToFit").attr('src');
    console.log(src);
         }, 2000);


    setTimeout(function(){


        var src = $('.iView1').contents().find(".shrinkToFit").attr('src');
    console.log(src);
         }, 3000);


    setTimeout(function(){


        var src = $('.iView2').contents().find(".shrinkToFit").attr('src');
    console.log(src);
         }, 3000);

         setTimeout(function(){


        var src = $('.iView3').contents().find("img").attr('src');
    console.log(src);
         }, 3000);


    })


</script>
</body>
 2
Author: Zisu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-24 09:29:04

Czy próbowałeś klasycznego, czekając na zakończenie ładowania za pomocą wbudowanej funkcji gotowej jQuery?

$(document).ready(function() {
    $('some selector', frames['nameOfMyIframe'].document).doStuff()
} );

K

 0
Author: Khb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-12-13 08:06:29