# iFrame Development Best Practices Author: Miguel Mota **Do** - use CSP on the iframed page; only load expected content - encrypt sensitive data in local storage; you can use window.crypto AES-CBC key - handle child iframe disconnects from parent page; set up interval ping and reconstruct iframe on disconnect - serialize objects when message passing; objects cannot contain reference when passed via postMessage - track injected iframes and destroy when necessary; choosing having singleton iframe vs multiple iframes, e.g. when script instantiated multiple times - include standard best practice security headers when serving iframe HTML page; e.g. X-XSS-Protection, X-Content-Type-Options, Strict-Transport-Security, etc - *always* specify target origin when sending message to child iframe; wildcard will send data to unwanted recipients **Don't** - don't assume messages sent to child are from trusted origin; *always* verify origin sender **Suggestions** - using the penpal library helps abstract message passing between child and parent page - local storage access can be blocked by browser settings or extension; check for local storage support and guide user - use sandbox attributes on iframe if possible; some browers might require specific iframe attributes for local storage - iframe.setAttribute('sandbox', 'allow-storage-access-by-user-activation allow-scripts allow-same-origin') - getting parent url in child iframe can be tricky; use ancestorOrigins if available const ancestorOrigin = document.location.ancestorOrigins && document.location.ancestorOrigins.length ? document.location.ancestorOrigins[0] : '' const parentUrl = window.location === window.parent.location ? window.location.href : ancestorOrigin || document.referrer || window.location.href - opening external urls by clicking element in iframe can be trickly; might need to send message to parent to trigger window.open