function fetchAndModifyContent(url, V) { let link; if (V === 'V1'){ link = url; } else { link = 'https://www.kartable.fr' + url; } console.log(link, V); fetch(link) .then(response => { if (response.ok) { return response.text(); } throw new Error(`Failed to fetch: ${response.statusText}`); }) .then(html => { const parser = new DOMParser(); const doc = parser.parseFromString(html, 'text/html'); const innerContent = doc.querySelector('.document--wrapper'); // const innerContentMain = innerContent.querySelector('document--wrapper'); if (innerContent) { let innerContentText = Array.from(innerContent.childNodes) .map(node => node.outerHTML || node.nodeValue) .join(''); assignContent(innerContentText); } else { console.log('Inner content not found'); } }) .catch(error => console.error(error)); } function assignContent(content) { const html = ` `; console.log('page opened'); const newWindow = window.open(); newWindow.location.href = "about:blank"; newWindow.document.write(html); newWindow.document.close(); } function replaceArticles() { var articles = document.querySelectorAll('.document-list__item'); articles.forEach(function (article) { var titleElement = article.querySelector('.document-list__title'); if (titleElement) { var articleText = titleElement.textContent; var button = document.createElement('button'); button.textContent = articleText; button.addEventListener('click', function () { var link = titleElement.getAttribute('href'); fetchAndModifyContent(link, 'V2'); }); article.parentNode.replaceChild(button, article); console.log('done'); } }); var articles = document.querySelectorAll('.document-readable'); articles.forEach(function (article) { var articleText = article.querySelector('h3').textContent; var button = document.createElement('button'); button.textContent = articleText; button.addEventListener('click', function () { var link = article.querySelector('h3 a'); var url = link.href; fetchAndModifyContent(url, 'V1'); }); article.parentNode.replaceChild(button, article); console.log('done'); }); var articles = document.querySelectorAll('.category'); articles.forEach(function (article) { var categoryTitle = article.querySelector('.category__title').textContent.trim(); var button = document.createElement('button'); button.textContent = categoryTitle; button.addEventListener('click', function () { var link = article.querySelector('.category__link'); var url = link.getAttribute('href'); fetchAndModifyContent(url, 'V1'); }); article.parentNode.replaceChild(button, article); console.log('done done') }); } replaceArticles();