I have the following code in the page example1.com:
<iframe src='//example2.com/embed.html' sandbox="allow-same-origin allow-modals allow-scripts allow-top-navigation allow-top-navigation-by-user-activation">
And I have the following code in my embed.html
<script>
try {
document.write('top url: ' + top.location.href)
}
catch (e) {
document.write('error' + e);
}
</script>
I get the error:
SecurityError: Blocked a frame with origin "https://example2.com" from accessing a cross-origin frame.
I only want to get properties of top object and I use the tag allow-same-origin in my iframe code. Doesn't this tag allow me to run the iframe as same-origin? If not, why do we have that tag?
example1.com and example2.com are a different domains therefore you have an issue with CORS (Cross-Origin Resource Sharing), but not with Content Security Policy. CORS allows direct access between the same domains or domain and its subdomain only.
You cannot get top.location.href property inside of cross origin iframe, but you can set it: top.location.href = 'https://any_domain.com/path.html' if allow-top-navigation presents in the sandox attribute or if sandbox is absent.
The sandbox attribute cannot help to bypass CORS restrictions, it only can imposes additional restrictions on the capabilities inside the iframe.
You can use window.postMessage() method for cross-origin communication between a page and an iframe embedded within it.