LoginSignup
54
49

More than 5 years have passed since last update.

iframeのクロスオリジンを倒す

Posted at

iframeで別ドメインを呼び出して操作したい

iframeでクロスオリジン対応をする必要があったのでメモ。

同じドメインでiframeを呼び出すことは問題ないが、異なるドメインをiframeで呼び出す場合、クロスオリジン対応をしないとiframe内部のHTMLにアクセスできない。

何が困るかって言うと「レスポンシブで高さが変わるから読み込み時のサイズに合わせてiframeの高さを中の要素に合わせたい」とかそういう時。

そういう時にはwindow.postMessageで子→親に情報を渡してやることで対応する。

子(iframe内のページ)

$(function(){
    var h = $('html').height();
    // 親におくる。第2引数は親のドメインを指定
    parent.postMessage(h, 'https://fuga.com/');
});

親(呼び出し側)

<iframe src="https://hoge.com/iframe.html"></iframe>
$(window).on('message', function(e){
    var height = e.originalEvent.data;
    $('iframe').css({'height': height + 'px'});
});

参照

Can I use
PostMessageを使ったクロスドメイン通信
jQuery doesn't support postmessage event?

54
49
0

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
54
49