目次
iframeとは

- 画面内に窓を作りその中に別ファイルを表示できます(上記図イメージ)。
- Google Mapやyoutubeの共有などでも使用されています。
iframeのサンプル
親の画面のファイル(test1.html)
<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="UTF-8" />
    <title>test</title>
  </head>
  <body>
    <p>元の画面</p>
    <iframe src="test2.html" width="150" height="150"></iframe>
  </body>
</html>
iframeを使用する側のファイルです。
9行目はiframeタグで表示するファイルを指定しています。
表示したいファイルは、srcで指定します。幅と高さも指定できます。
iframe内に表示されるファイル(test2.html)
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>test</title>
</head>
<body>
  <p>テスト項目1</p>
  <p>テスト項目2</p>
  <p>テスト項目3</p>
</body>
</html>
iframe内に表示されるファイルです。特別な記載は必要ありません。
iframeで制限をコントロールする(sandbox)
sandboxの指定で制限をコントロールできます。
<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="UTF-8" />
    <title>test</title>
  </head>
  <body>
    <p>元の画面</p>
    <iframe
      src="test2.html"
      width="200"
      height="100"
      sandbox="allow-same-origin allow-forms allow-scripts"
    ></iframe>
  </body>
</html>
sandboxにキーワードを指定します。
allow-same-originは、same-originを許可します。
allow-scriptsは、scriptsを実行できるようになります。
allow-formsは、フォーム送信を許可します。
sandboxがない場合はすべてが制限されます。
以下は、MDNのiframeのsandboxリンクです
https://developer.mozilla.org/ja/docs/Web/HTML/Element/iframe#attr-sandbox
子画面から親の画面を操作する
| parent.document | 
子画面から親の画面を操作する場合は、子画面でparent.documentを使用します。
親の画面のファイル(test1.html)
<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="UTF-8" />
    <title>test</title>
  </head>
  <body>
    <p id="p1">元の画面</p>
    <iframe src="test2.html" width="150" height="150"></iframe>
  </body>
</html>
iframe内に表示されるファイル(test2.html)
<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="UTF-8" />
    <title>test</title>
  </head>
  <body>
    <p>テスト項目1</p>
    <input type="button" id="button1" value="ボタン" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script>
      $("#button1").click(function () {
        $("#p1", parent.document).css("background", "yellow");
      });
      
    </script>
  </body>
</html>
15行目は、親画面の8行目の背景色を黄色に変えます。
注意
この操作を行う場合は、ファイルがWebサーバーに配置されていることが必要です。
単にローカルのhtmlファイルのやり取りの場合以下のエラーが出て実行できません。
| Uncaught DOMException: Blocked a frame with origin "null" from accessing a cross-origin frame. | 
関連の記事
