I get this question a lot — especially from people building iframe-based components with zoid. The question is “how do I whitelist multiple domains with X-FRAME-OPTIONS?”
The answer is pretty simple (and it works for any iframe): have the client pass along the domain when you create the iframe! Here’s an example.
First, on the client, let’s create our iframe, and pass along the domain:
// Set up the url for our iframe, and get the current domainvar url = 'https://www.my-site.com';
var domain = window.location.protocol + '//' + window.location.host;// Create the iframevar iframe = document.createElement('iframe');
document.body.appendChild(iframe);// Set the src, and pass along the domain as a query paramiframe.src = url + '?domain=' + domain;
Then on our server side, we can make the decision whether or not to allow the domain:
// Set up a whitelist of domains that can render us in an iframevar XFRAME_WHITELIST = [ 'https://x.com', 'https://y.com' ];// If the domain matches, allow iframes from that domainif (XFRAME_WHITELIST.indexOf(req.query.domain) !== -1) {
res.header('X-FRAME-OPTIONS', 'ALLOW-FROM ' + req.query.domain);
}
This example is in node.js / express.js, but this logic works no matter your server platform.
You can also use thereferer header instead of a query param, but note that referer is not guaranteed to be present 100% of the time.
This also works perfectly if you’re building a cross-domain component using zoid:
var url = 'https://www.mysite.com/mycomponent';
var domain = window.location.protocol + '//' + window.location.host;
var MyComponent = zoid.create({
url: url + '?domain=' + domain
});
And if you’re interested in learning more about using zoid to create cross-domain components, please feel free to take a look:
Thanks!
'Study > JavaScript' 카테고리의 다른 글
클라이언트의 Javascript 코드를 숨기는 방법 (0) | 2021.11.18 |
---|---|
[Javascript] 마우스 이벤트(event) (0) | 2021.11.12 |
웹 개발자로서 생산성 향상을 볼 수 있는 7가지의 스킬 (0) | 2021.11.11 |
JavaScript 개발자를 위한 최고의 VS Code 확장프로그램 (0) | 2021.11.11 |
JavaScript의 이벤트 처리 TIp (0) | 2021.11.11 |