LoginSignup
86
92

More than 5 years have passed since last update.

Javascriptでのiframe操作tips(iframeの中身を差し替える)

Last updated at Posted at 2014-03-08

追記(2016/05/05)

コメントでご指摘いただきました。
過去のソースにアクセス出来ない&Javascriptの知識が浅いので経緯がわからない状態ですが、
iframe elementの取得方法と、iframe内のコンテンツの更新方法を下記のように置き換えないと動かないようです。ご注意ください。

document.getElementById('iframe_id')[0].contentDocument.location.replace('target_url or target_path');



document.getElementById('iframe_id').contentWindow.location.replace('target_url or target_path');

追記ここまで。
以下、2014年に投稿した記事です。


  コンテンツの更新システムを作る場合などに、iframeを使ってプレビューを表示したい
  カレンダーの日付クリックイベントを拾って、iframeの中身を差し替えたい(iframeのURLを差し替えたい)

なんて実装をする時にはまったのでメモ。

iframeを更新(=リロード)する

location.reloadを使います。
reload(true)でスーパーリロードになります。

jQuery

$('#iframe_id')[0].contentDocument.location.reload(true);

素のJavascript

document.getElementById('iframe_id')[0].contentDocument.location.reload(true);

iframeのコンテンツを差し替える(別のURLからコンテンツを取得する)

iframeの中身を差し替えたい場合は、location.srcを書き換えてlocation.reloadしてもダメ。
location.replaceしましょう。

jQuery

$('#iframe_id')[0].contentDocument.location.replace('target_url or target_path');

素のJavascript

document.getElementById('iframe_id')[0].contentDocument.location.replace('target_url or target_path');

Sample

$('#iframe_id')[0].contentDocument.location.replace('/preview/show/20140320');

↑2014/03/20時点のコンテンツプレビューが見たい = previewコントローラのshowアクションに年月日パラメータ(20140320)を引き渡した結果をiframe内に表示する。というイメージ。

86
92
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
86
92