1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

防ごう。自己参照iflameの無限ループ。

Posted at

ふと思いついたけど見当たらなかったので書きます。
初心者過ぎてわからないのですが、そもそもiflame要素での自己参照って使うことあるんですかね?

完成図

image.png

方針

iflameで参照するURLに階層の深度(depth)をパラメータとして付け加え、その値によって再帰構造を繰り返すか判断する。

作成したコード

<!DOCTYPE html>
<html lang="ja">

<head>
    <meta charset="UTF-8">
    <title>自己参照iframeサンプル</title>
    <style>
        body {
            font-family: sans-serif;
            text-align: center;
            margin: 50px;
        }

        iframe {
            margin-top: 20px;
            border: 2px solid #aaa;
            width: 80%;
            height: 300px;
        }
    </style>
</head>

<body>
    <h1>自己参照iframeテスト</h1>
    <div id="content"></div>

    <script>
        const MAX_DEPTH = 3; // 最大階層

        // 現在のdepthをURLから取得
        const params = new URLSearchParams(window.location.search);
        const depth = parseInt(params.get('depth') || '0', 10);

        // 今のdepthを表示
        document.getElementById('content').innerHTML = `<p>現在の階層: ${depth}</p>`;

        // 最大階層未満なら自己参照iframeを表示
        if (depth < MAX_DEPTH) {
            const nextDepth = depth + 1;
            const iframe = document.createElement('iframe');
            iframe.src = `?depth=${nextDepth}`;
            document.getElementById('content').appendChild(iframe);
        } else {
            document.getElementById('content').innerHTML += `<p>最大階層に到達しました!</p>`;
        }
    </script>
</body>

</html>

注意点

  • 再帰の階層を増やしすぎるとブラウザが重くなる
  • サーバーによっては自己参照を禁止していることもあるらしい(GitHub PagesはOKでした)
  • スマホブラウザの負荷を考えてあげてください
  • ブラウザ側でも回数やら個数やらの制限があるかもしてない

まとめ

URLに情報を書き足すことでiflameの中の動作をルートと変更することができた。
最近再帰構造のあるゲームが流行ってたりする気がするので、ゲーム制作者さんの選択肢が広がるといいなと。

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?