Forums

iframes inside Jupyter notebooks

Running locally on my computer I can create and iframe inside a Jupyter notebook. For example:

# Display the associated webpage in a new window
import IPython
url = 'some url....'
iframe = '<iframe src=' + url + ' width=700 height=350></iframe>'
IPython.display.HTML(iframe)

But when I run the same cell in a notebook on PythonAnywhere the output cell is blank.

Is there a trick to making this work?

That's an interesting question! I just tried it in a notebook of my own, and discovered some interesting stuff.

Firstly I tried with setting url to http://www.google.com/. This failed in the way you describe, and when I looked at the browser's error console (in Chrome, you go to the "hamburger" menu at the top right, then "more tools", then "developer tools", then select the "Console" tab) I saw the error

jquery.min.js: Mixed Content: The page at 'https://www.pythonanywhere.com/user/giles/ipython_notebooks/view/test_iframe.ipynb' was loaded over HTTPS, but requested an insecure resource 'http://www.google.com/'. This request has been blocked; the content must be served over HTTPS.

So, what was happening was that the browser noted that my notebook had been loaded over HTTPS, and I was trying to load a website using non-secure HTTP, and it blocked it. This is good security practice.

Next, I tried using the secure URL for Google, https://www.google.com/. I got another error in the error console:

Refused to display 'https://www.google.co.uk/?XXXXX' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.

(I've replaced the precise URL's query parameters with XXXXX just in case there was private information in there.)

What that meant was that Google, in their HTTP headers, include something telling browsers that their site should never be embedded in an iframe, which sounds like a sensible security precaution.

So, finally, I chose a site that I knew could be embedded (I won't mention which), and used that. It worked!

My guess is that something similar is going on with your choice of site. Most likely, the URL you're using is HTTP instead of HTTPS, and that's the cause, but if you look at the browser's error console you should get a definite answer.

Yes! You are correct. I opened the Javascript console and saw the error message you mentioned for trying to embed non-secure content. I was trying to do this for a teaching notebook for a new class I'm developing, but if I want to used PythonAnywhere for the class it looks like I'll need to use an alternative to iFrames.

Thanks for your help. Much appreciated!

Unless there's an HTTPS version of the site in question...? They might not have the same restrictions against embedding it inside an iframe. Worth a try, at least!