SecurityError: Failed to read the 'contentDocu

2019-08-30 23:36发布

问题:

I have on a webpage an iframe element that loads my other website, and I'm trying to access the content of that webpage in an iframe. This works when both websites are on localhost, but on different domains I get this error : SecurityError: Failed to read the 'contentDocument' property from 'HTMLIFrameElement Blocked a frame with origin "http://site1.com" from accessing a frame with origin "http://site2.com". Protocols, domains, and ports must match.

I have control over both websites, I can disable headers or add new. Is there a technical way to enable first site reading the contents of the iframe ?

回答1:

You need to set the Access-Control-Allow-Origin to allow cross-origin resources. This shouldn't be a problem, since you control both domains.

If you're using PHP (for example), you could set the header on site2 like:

header('Access-Control-Allow-Origin: site1.com');

You can use a similar function for other server software.