Search code examples
javascripthtmlblob

reference files from blob object url when path from root might change


I'm generating the contents of a container (iframe) from data stored/generated in the hosting page.

parent.App.Plugins.GetInstance(obj).Compile(obj.content).then((html) => {
    var blob = new Blob([html],{type:"text/html"});
    var url = URL.createObjectURL(blob);
    window.location.href = url;
});

if the html of the page inside the blob wants to load content relative to the path of the parent (host) page, what is the relative url to use?

for instance, if inside the generated html there was

<html>
<head>
  <script src="https://unpkg.com/jquery/dist/jquery.min.js"></script>
  <script src="./modules/loader.js" type="module"></script>
  <script src="js/main.js"></script>
</head>
<body>
  <img src="https://images.unsplash.com/photo-1472740378865-80aab8e73251">
  <img src="/images/some-file.jpg">
</body>
</html>

the external references to files will work (https://blah etc), not files served from my server (js/main.js, /images/file.jpg etc).


Solution

  • Blob URLs are essentially temporary file:// URLs that are associated with a domain, but they're still stored on your computer, so when referencing files from the original domain, it's necessary to use the absolute path. <img src="https://youwebsite.com/images/some-file.jpg" />