Dynamically generated iframe content is empty

In my localhost, I use the following JavaScript to create an iframe with src and add it to the document:

 $('#preview').html('<iframe src="http://google.com/"></iframe>'); 

IFrame shows, but not content. In firebug, this is simple:

 <iframe src="http://google.com/"> <html> <head></head> <body></body> </html> </iframe> 

When I execute $('iframe').attr('src','http://google.com/'); on the console, the browser loads (says "Waiting for google.com ..."), it seems to update the contents of the iframe. But then again, it is empty.

If I installed it on a local page, the content will load.

Is it because of the same origin policy? I am not so informed about this. I did some google search and I'm confused because some sites say that it is ok to include an iframe with src that does not belong to your own domain, and some say that this is not possible.

By the way, since I'm still testing on localhost, will this work if I upload it to the server somewhere? (but src iframe will still be in a different domain)

reference

+6
source share
2 answers

If you checked the browser error console, you would see this message:

Refuses to display the document, because display is prohibited using X-Frame-Options.

So, this is not a mistake on your part, but a deliberate action on the part of Google.

Two options for X-Frame-Options :

  • deny - lack of rendering inside the frame and
  • sameorigin - no rendering if the source of the mismatch

Literature:

+12
source

Yes, the code is prohibited by the same origin policy. Read here

Suppose you have a domain http://www.example.com , then you can probably get the following results when calling pages via iframes:

 Compared URL Outcome Reason --------------------------------------------------------------------------------------------- http://www.example.com/dir/page.html Success Same protocol and host http://www.example.com/dir2/other.html Success Same protocol and host http://www.example.com:81/dir2/other.html Failure Same protocol and host but different port https://www.example.com/dir2/other.html Failure Different protocol http://en.example.com/dir2/other.html Failure Different host http://example.com/dir2/other.html Failure Different host (exact match required) http://v2.www.example.com/dir2/other.html Failure Different host (exact match required) 

You are now calling google.com, which is a cross-domain problem. To get around this, JSONP can help you. It uses an open script policy for <script> to get JSON from cross domains.

+4
source

Source: https://habr.com/ru/post/914426/


All Articles