iframe src allows all origins but still receiving

2020-05-10 02:06发布

问题:

I manage the frontend of siteA and have an iframe on the page with a src pointing to a resource from siteB. This is meant to be an embeddable resource (its a video embed) used by other vendors & clients so the response headers of siteB are set to Access-Control-Allow-Origin *. And all URLs involved are https.

I have a screenshot here of the headers here from the src url in dev tools:

However, I’m still receiving cross-origin errors when trying to query the iframe document to check if a specific element is present.

I’m not trying to modify any content but want to make simple UI decisions depending on the content.

To no avail I’ve tried:

  • standard jQuery methods like $(‘iframe’).contents().find()
  • $.get requests to retrieve the html response and see if it includes a specific string

Am I missing something? Getting over this hurdle would be a major win for our project.

回答1:

You could apply the Access-Control-Allow-Origin header which will allow you to read ajax responses from another domain, eg:

Access-Control-Allow-Origin: *

But this header will NOT allow you to access a rendered iframe from another domain due to the Same Origin Policy. But it would allow you to make a new ajax (GET) request to the iFrame's domain and then work with the response.

This stackoverflow question explores some ways that the same-origin-policy can be bypassed, some of the suggestions might help you, but it depends what you're trying to achieve.