I am developing a JavaScript library which users would include in their website. a common theme across 3rd party libraries is that they are loaded in a n iframe. (ex you tube) . Is there any specific reason for that from security point of view?

my library was initially designed to be loaded in iframe but because of some very particular cases i think only way i have is to somehow load it directly in DOM.


Loading javascript in an iframe "automatically" protects the parent from unwanted changes with respect to some flavour of the Same Origin Policy that browsers adopt.

So they limit the damage that a third party library can do when attempting to change your original web content; for example, they may modify an legitimate link to some other same-looking place that performs some phishing and steals user's information, cookies, etc.

This is not the only way where the same origin policy is implemented, but it is quite an easy one. In the case you need (safe) interaction between the parent and the iframe, one of the ways is to perform postMessage calls.

|improve this answer|||||
  • To add to this: if your library requires loading directly in the main page's DOM, people are going to be much less likely to use it. There's very little that a malicious or compromised script can do from within a cross-origin iframe - especially if the sandbox attribute is used - but in the page directly (or in a same-origin unsandboxed iframe) anybody that loads your script from your server/repo is basically giving you full persistent XSS on their site. – CBHacking Jul 20 '19 at 22:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.