Home > Software engineering >  Access relative files from a sandboxed iframe
Access relative files from a sandboxed iframe

Time:11-30

I want to understand if the following scenario would work - Assume, I the following setup of files

parent.html
style.css
logic.js
child.html

parent.html is as follows -

<html>
<head>
<link href="style.css" rel="stylesheet" />
<script src="logic.js"></script>
</head>
<body>
<h1>Hello, World</h1>
<iframe sandbox src="child.html">
</body>
</html>

Assume that child.html is

<html>
<head>
<link href="style.css" rel="stylesheet" />
<script src="logic.js"></script>
</head>
<body>
<h1>Hello, from Child Page</h1>
</body>
</html>

Assume that parent.html is served and consumed like - example.com/parent.html

My Question is - will the relative paths accessed from child.html (logic.js & style.css files) work ? If so, why ?

I tried this setup locally ( just hosted a simple http server ) and things seems to work.

I was of the opinion that this wouldn't work given that child.html is loaded in a sandboxed iframe, which gets a unique origin and so, there is a no base URL to resolve the relative paths against.

thanks,

CodePudding user response:

None of the restrictions imposed by the sandbox attribute restrict loading of resources into a document.

You can link to scripts and stylesheets freely.

I was of the opinion that this wouldn't work given that child.html is loaded in a sandboxed iframe, which gets a unique origin and so, there is a no base URL to resolve the relative paths against.

Changing the origin doesn't change the base URL. It only affects things which pay attention to the Same Origin Policy. For example, if the script tried to fetch('/').then(res => res.text()) it would fail because the fetch API implements the Same Origin Policy. Likewise if you said <link href="style.css" rel="stylesheet" crossorigin="anonymous"> it would fail as the crossorigin attribute adds a dependency on the SOP.

CodePudding user response:

Yes, the relative paths should work in this scenario. The parent page and the child page both have the same origin, so the browser can access the same files from both pages. The sandboxed iframe does get its own origin, but the browser is still able to access the same files from both pages.

  • Related