Skip to content
Advertisement

Is it possible for an html file to access loaded html variable using fetch?

lets say I have a page.html file with this content:

<html>
<body>
    <h1>Hello World</h1>
    <script>var foo_data = "abc"; </script> 
</body>
</html>

and then on my main.html file I used:

<script>
  fetch('/page.html')
    .then(response => response.text())
    .then(data => {
          document.getElementById('page-content').innerHTML = data;
          console.log(foo_data); // Will not work
    })
</script>

Is there a way to access foo_data on my main.html file or are there better ways to do this?

Advertisement

Answer

Here is eval() method. Basically the idea is parse html in data variable, and execute <script> elements with eval:

fetch('/page.html')
    .then(response => response.text())
    .then(data => {
          const html = document.createRange().createContextualFragment(data);
          //this is unnecesary, unless you need to display html
          document.getElementById("page-content").innerHTML = data;
          
          for(let i = 0, scripts = html.querySelectorAll("script"); i < scripts.length; i++)
            eval(scripts[i].textContent); //execute scripts

          console.log(foo_data);
    })
    .catch(er => console.error(er));
    
    
/* ignore below */

async function fetch()
{
  return new Promise((resolve, reject) =>
  {
    resolve(new Promise((resolve, reject) =>
    {
      resolve({text: () => `<html>
<body>
    <h1>Hello World</h1>
    <script type="javascript">var foo_data = "abc";</script> 
</body>
</html>`});
    }))
  })
}
<div id="page-content"></div>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement