You might have heard that if you create an iframe, your site might becomes vulnerable to cross-site attacks. And this is true. So there is a way of creating an isolated iframe in order to make it more secure.
This can be achieved just by using the attribute sandbox
which enables an extra set of restrictions for the content in the iframe. And being capable of enabling only the required tooling for your iframe with the following attribute values
:
allow-forms
: Allows form submissionallow-modals
: Allows to open modal windowsallow-orientation-lock
: Allows to lock the screen orientationallow-pointer-lock
: Allows to use the Pointer Lock APIallow-popups
: Allows popupsallow-popups-to-escape-sandbox
: Allows popups to open new windows without inheriting the sandboxingallow-presentation
: Allows to start a presentation sessionallow-same-origin
: Allows the iframe content to be treated as being from the same originallow-scripts
: Allows to run scriptsallow-top-navigation
: Allows the iframe content to navigate its top-level browsing contextallow-top-navigation-by-user-activation
: Allows the iframe content to navigate its top-level browsing context, but only if initiated by user
<iframe src="demo_iframe_sandbox.html" sandbox="allow_scripts"></iframe>
If some some reason you are using injected HTML, as it is useful for many frameworks like Hugo, or you just want to type the inline HTML, you can use the attribute srcdoc
which lets you do this securely. Which is the same as src
attribute but not cross domain and other differences. Such as being secure in in legacy-browsers and secure browsers.
<iframe
srcdoc="
<html>
<head>
<!-- Your content goes here -->
</head>
<body>
<!-- Your content goes here -->
</body>
</html>
"
sandbox="allow_scripts"
></iframe>
For a Hugo
shortcode:
<iframe
srcdoc="{{safeHTMLAttr .Inner}}"
frameborder="0"
sandbox="allow-scripts"
>
<iframe></iframe
></iframe>