49

ページの iframe が新しいページの読み込みを開始したことを検出するにはどうすればよいですか?

私たちの状況は次のとおりです。

  • iFrame のコンテンツが変化し始めたら、「読み込み中」のアニメーションを表示し、検索ボックスを非表示にする必要があります。
  • 「iframe の読み込みが終了しました」イベント (アニメーションを非表示にするため) を処理する方法は知っていますが、最初の「変更の開始」イベントをキャッチする方法はわかりません...

注: jquery の「クリック」フックをメニューのリンクに取り付けることができます。ただし、iframe コンテンツ内には多くの相互参照リンクがあり、それらにも「変更」イベントが適用されます。そのため、ユーザーが iframe 内のリンクをクリックしたとき、またはjavascript を介して iframe src が変更されたときにイベントをキャッチする必要があります。

4

4 に答える 4

29

私は次の解決策を思いつきました-これは、iframeコンテンツとホストウィンドウのコンテンツを制御するためにのみ可能です

iframe 内で、次のスクリプトをページ フッターに追加します (すべてのページが同じテンプレートを使用するため、これは 1 つのファイルへの変更です)

<script>
window.onunload = function() {
    // Notify top window of the unload event
    window.top.postMessage('iframe_change', '*');
};
</script>

ホスト ウィンドウ内にこのスクリプトを追加して、iframe の状態を監視します。

function init_content_monitor() {
    var content = jQuery('.iframe');

    // The user did navigate away from the currently displayed iframe page. Show an animation
    var content_start_loading = function() {
        alert ('NOW: show the animation');
    }

    // the iframe is done loading a new page. Hide the animation again
    var content_finished_loading = function() {
        alert ('DONE: hide the animation');
    }

    // Listen to messages sent from the content iframe
    var receiveMessage = function receiveMessage(e){
        var url = window.location.href,
            url_parts = url.split("/"),
            allowed = url_parts[0] + "//" + url_parts[2];

        // Only react to messages from same domain as current document
        if (e.origin !== allowed) return;
        // Handle the message
        switch (e.data) {
            case 'iframe_change': content_start_loading(); break;
        }
    };
    window.addEventListener("message", receiveMessage, false);

    // This will be triggered when the iframe is completely loaded
    content.on('load', content_finished_loading);
}
于 2013-06-26T09:37:14.067 に答える