3

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.

4

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

E.g., this will only allow frame content from the same domain:

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

Instead of 'self' you can also specificy 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/Edge.

  • 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? – Dog eat cat world Mar 9 '17 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 '17 at 20:15
  • Of course, I mixed these things up. Thanks for the clarification @Arminius – Dog eat cat world Mar 9 '17 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 '17 at 11:56
  • @gordon613 Thanks for catching that, I added a note. – Arminius Mar 14 '17 at 22:14

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.