6

How can I restrict my iFrame to use only local (i.e. not from other websites) content? My question is the reverse of the question as how to restrict other sites from using my site in an iframe.

I am using Tomcat/Java/JSP.

0

1 Answer 1

9

You can set a Content-Security-Policy header with the child-src directive.

For example, this will only allow frame content from the same domain:

Content-Security-Policy: child-src 'self'

Instead of 'self' you can also specify a particular origin.

Here is a simple demo (the meta tag is used to simulate the header). Only the first frame should load:

<meta http-equiv="Content-Security-Policy" content="child-src http://example.com/">
<iframe src="http://example.com/"></iframe>
<iframe src="http://example.org/"></iframe>

Note that this works in Firefox and Chrome but isn't supported in IE and older browsers.

5
  • Before CSP, this used to done with the header "X-Frame-Options: SAMEORIGIN". Can you expect that all browsers support CSP, or should you add this for backwards compatibility? Mar 9, 2017 at 19:54
  • 1
    @Dogeatcatworld As I understand it, this is precisely what OP does not want. X-Frame-Options prevents embedding from the frame's perspective, not from the perspective of the parent.
    – Arminius
    Mar 9, 2017 at 20:15
  • Of course, I mixed these things up. Thanks for the clarification @Arminius Mar 9, 2017 at 20:59
  • Hi @Arminius - just to add that this solution doesn't work for IE - see caniuse.com/#search=csp Here is a link to test if csp works in one's browser content-security-policy.com/browser-test
    – gordon613
    Mar 14, 2017 at 11:56
  • @gordon613 Thanks for catching that, I added a note.
    – Arminius
    Mar 14, 2017 at 22:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .