[SalesForce] Content security policy error while loading apex iframe

Issue: We get CSP (Content Security Policy) error with our Visualforce page integration.

The issue is that when we access this in sandbox testing, we find that our content is wrapped in an iframe, and that iframe also contains an iframe.

The outer iframe does not seem to have a URL, and so we cannot exclude it from our CSP whitelist.

apex putting the iframe dynamically inside another iframe that is not having any src, that is why we are not able to whitelist the domain that can open our site into iframe.

  • VisualForce page code
<apex:page standardController="Opportunity" extensions="CustomOpportunityController">
  <apex:iframe src="https://my-site.com" width="100%" height="900px" scrolling="true" id="theIframe" />
</apex:page>
  • Below is the sample iframe inside the iframe.
<iframe allow="geolocation *; microphone *; camera *" frameborder="no" height="1000px" id="0661b0000004nmw" marginheight="0" marginwidth="0" name="0661b0000004nmw" scrolling="yes" title="HelloWorld" width="100%">
  <iframe src="https://my-site.com"> </iframe>
</iframe>
  • Error log from developer console of browser.
    [Report Only] Refused to display 'https://my-site.com' in a frame because an ancestor violates the following Content Security Policy directive: "frame-ancestors 'self' *.salesforce.com".

Please let me know if there is a way to resolve the content security error in this case!

Best Answer

From what you've written, I believe you're embedding your Visualforce page in a record page layout in the Classic interface. Visualforce in a page layout is always wrapped in that iframe with the size and other attributes you set in the page layout editor. That iframe's presence is not the issue.

The CSP Trusted Sites documentation specifies that these settings only apply to the Lightning UI, and says:

NOTE To enable corresponding access for Visualforce or Apex, create a Remote Site.

So you need to add https://my-site.com as a Remote Site, under Remote Site Settings in Setup.

If you are trying to use this Visualforce page inside of Lightning, the recommendation is basically, don't. From Understanding the Salesforce App Container in the Visualforce Developer Guide:

Avoid using <apex:iframe> on a Visualforce page within the Salesforce app container. Only use this tag if you really understand iframes and how they affect the DOM and JavaScript.