I'd like to use social sharing widgets (e.g. Facebook Like, Twitter Tweet, etc) on my site, but I don't want to directly embed third-party script tags. I'd like my site to only run either trusted or sandboxed code.
Is there a solution to this? Or do I have to choose between not having the buttons at all and running untrusted JavaScript?
Additional context: I'd like to run my entire site on HTTPS, but I also want to have sharing buttons. I don't want to potentially leak secure cookies to Facebook or Twitter.
If you don't trust third-party JavaScript (and I don't blame you, it's scary!), your best bet is to use the iframe
implementations that these social networks provide. For instance, you can include a Facebook "Like" button by adding the following frame to your site:
<iframe src="//www.facebook.com/plugins/like.php?href=[PAGE_URL_GOES_HERE]&send=false&layout=button_count&width=450&show_faces=true&font&colorscheme=light&action=like&height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:21px;" allowTransparency="true"></iframe>
https://dev.twitter.com/docs/tweet-button#using-an-iframe has details on a similar setup for Twitter.
Encapsulating the code in an iframe
gives you some measure of protection against the content of the frame, as it can't reach up into the parent to grab data or manipulate your code.
You can increase the level of protection by sandboxing the iframe
via the (cleverly named) sandbox
attribute. For instance:
<iframe sandbox="allow-script allow-same-origin" src="..."></iframe>
would load a page into an iframe
, and allow it to run script with access to its origin (but still not the parent's origin). It would not, however, be able to navigate the top level document, load plugins, etc. Sandboxing is supported in Chrome, Safari, Firefox 18+, and IE9 (I think. Might be 10.).