メインページで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を自分のホームページのファイルツリーの表示とファイルの中身の表示に使おうと思う。
戻るボタンと進むボタンも入れる。