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

More than 1 year has passed since last update.

iframe内でリンクを貼り、そのリンクをクリックするとiframe内で遷移する方法

Posted at

メインページでiframe内の遷移を管理し、戻るボタンを実装する方法をchatGPTに聞く。
chatGPT「・・・動作確認をするためには、ローカルサーバーで実行することをお勧めします。さらに、この例ではすべてのファイルが同じオリジン(同じドメイン)に配置されていることを前提としています。親ページのHTMLファイル(index.html)を作成し、iframe要素と戻るボタンを追加します。」

親ページの作成

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Iframe Navigation</title>
</head>
<body>
  <iframe id="my-iframe" src="iframe-content.html" width="600" height="400"></iframe>
  <button id="iframe-back">戻る</button>
  <script src="main-script.js"></script>
</body>
</html>

iframe-content.htmlファイルを作成し、リンクを追加する。

iframe-content.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Iframe Content</title>
</head>
<body>
  <a href="https://example.com" class="controlled-link">Visit Example.com</a>
</body>
</html>

main-script.jsファイルを作成し、メインページでiframe内のリンクの遷移と戻るボタンを制御する。

const iframe = document.getElementById("my-iframe");
const iframeBackButton = document.getElementById("iframe-back");

let iframeHistory = ["iframe-content.html"];

iframe.addEventListener("load", function () {
  const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
  const links = iframeDoc.querySelectorAll("a");

  links.forEach((link) => {
    link.addEventListener("click", function (event) {
      event.preventDefault();
      iframeHistory.push(link.href);
      iframe.src = link.href;
    });
  });
});

iframeBackButton.addEventListener("click", function () {
  if (iframeHistory.length > 1) {
    iframeHistory.pop(); // 現在のページを履歴から削除
    const previousUrl = iframeHistory[iframeHistory.length - 1];
    iframe.src = previousUrl;
  }
});

<感想>

iframeを自分のホームページのファイルツリーの表示とファイルの中身の表示に使おうと思う。
戻るボタンと進むボタンも入れる。

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