14

On my localhost, I am using the following JavaScript to create an iframe with src, and add it to the document:

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

The iframe shows but not the content. In firebug, it's just:

<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..."), then seems to refresh the content of the iframe. But again, it's empty.

If I set it to a local page, though, the content is loaded.

Is this because of the same origin policy? I'm not so informed about it. I did some googling and I'm confused because some sites say that it's okay to include an iframe with src that doesn't belong to your own domain, and some say it's not possible.

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

Help?

2 Answers 2

15

If you'd checked your browser's error console, you'd have seen this message:

Refused to display document because display forbidden by X-Frame-Options.

So, this isn't an error on your part, but a deliberate action on the part of Google.

The two options for the X-Frame-Options are:

  • deny - no rendering within a frame, and
  • sameorigin - no rendering if origin mismatch

References:

1
  • Thank you very much. The 3rd link (SO) was helpful as I'm trying to load a google map into the iframe.
    – Obay
    Commented Apr 28, 2012 at 19:22
4

Yes the code is forbidden because of same origin policy. Read here

Suppose you own the domain http://www.example.com then you can probably have following results, when you call pages through 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)

Now, you are calling google.com, which is a cross domain issue upon you. To get around such a problem, JSONP can help you out. It uses open script policy for <script>, to retrieve JSON from cross domains.

Not the answer you're looking for? Browse other questions tagged or ask your own question.