I need your help, I have a parent A page with an integrated B iframe.
When I click on a link in the B iframe, I want to retrieve the title and url of the clicked link and pass it to the main page to simulate navigation.
It’s essential that the page doesn’t reload.
To do this, I use the javascript message API and the history API.
This works fine, but my history doesn’t work properly anymore, as I have to click twice on previous for it to work.
Or I can’t get the corresponding url in the url bar.
I know that what I’m trying to do is rather complicated, but if anyone has a solution or a clue, I’d love to hear from you.
Thanks in advance
Main page :
<iframe id="childFrame1" name="childFrame1" src="child1.html" width="600" height="400"></iframe>
<script>
// Ajoute un gestionnaire pour l'événement popstate dans le parent
window.addEventListener('popstate', function(event) {
alert('pop')
console.log(event.state)
if (event.state && event.state.url) {
const iframe = document.querySelector("#childFrame1");
iframe.src = event.state.url;
}
});
// Écoute les messages provenant des iframes
window.addEventListener('message', function(event) {
if (event.data.type === 'updateUrl') {
// Met à jour l'URL et le titre sans ajouter une nouvelle entrée à l'historique
history.pushState({ url: event.data.url, title: event.data.title, source: event.data.source }, event.data.title, event.data.url);
document.title = event.data.title;
}
});
</script>
Iframe code:
<a href="/page1" data-title="Page 1">Link to Page 1</a>
<a href="/page2" data-title="Page 2">Link to Page 2</a>
<script>
function navigate(url, title) {
window.parent.postMessage(
{
type: "updateUrl",
url: url,
title: title,
source: "iframe"
},
"*"
);
}
// Gestion des boutons
document.getElementById("navigate1").addEventListener("click", function () {
navigate("/page1", "Page 1");
});
document.getElementById("navigate2").addEventListener("click", function () {
navigate("/page2", "Page 2");
});
// Gestion des liens
document.querySelectorAll('a').forEach(function(link) {
link.addEventListener('click', function(event) {
event.preventDefault(); // Empêche le comportement par défaut
navigate(link.getAttribute('href'), link.getAttribute('data-title'));
location.assign(link.href);
});
});
</script>
From what I’ve read, the only way to change the url is to use pushState, which is a problem in my case.