LoginSignup
21
18

More than 5 years have passed since last update.

jQueryでiframeと親window同士でイベントをtriggerする

Last updated at Posted at 2015-04-19

jQueryをつかってiframeの中へイベントをtriggerする、あるいは、iframeの中から親windowへイベントをtriggerするのにハマったのでシェアしておきます。

親ウィンドウでもiframe内でもjQueryが読み込まれてる前提です。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
</head>
<body>
  <iframe src="/iframe/" name="myIframe" frameborder="0"></iframe>
</body>
</html>

親windowからiframeのdocumentへイベントをtriggerする

document.myIframe.$(document.myIframe.document).trigger('someCustomEvent');

ポイントは子フレームスコープのjQueryを使うところですね。$(document.myIframe.document).trigger(...)だと受け取れませんので注意してください。

逆も同じ要領です。
iframeから親windowのdocumentへイベントをtrigger。

parent.$(parent.document).trigger('someCustomEvent');

受けとる側は普通です。

$(document).on('someCustomEvent', function(e){

});
21
18
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
21
18