Widget - Iframe versus JavaScript - javascript

I have to develop a widget that will be used by a third party site. This is not an application to be deployed in a social networking site. I can give the site guys a link to be used as the src of an iframe or I can develop it as a JavaScript request.
Can someone please tell me the trade offs between the 2 approaches(IFrame versus JS)?

I was searching about the same question and I found this interesting article:
http://prettyprint.me/prettyprint.me/2009/05/30/widgets-iframe-vs-inline/
Widgets are small web applications that can easily be added to any web
page. They are sometimes called Gadgets and are vastly used in growing
number of web pages, blogs, social sites, personalized home pages such
as iGoogle, my Yahoo, netvibes etc. In this blog I use several
widgets, such as the RSS counter to the right which displays how many
users are subscribed to this blog (don’t worry, it’ll grow, that’s a
new blog ;-) ). Widgets are great in the sense that they are small
reusable piece of functionality that even non-programmers can utilize
to enrich their site.
I’ve written several such widgets over the time both “raw” widgets
that can get embedded in any site as well as iGoogle gadgets which are
more structured, worpress*, typepad and blogger widgets, so I’m happy
to share my experience.
As a widget author, for widgets that run on the client side (simple
embeddable HTML code) you have the choice of writing your widget
inside an iframe or simply inline the page and make it part of the dom
of the hosting page. The rest of the post discusses the pros and cons
of both methods.
How is it technically done? How to use an iframe or how to implement
an inline widget?
Iframes are somewhat easier to implement. The following example
renders a simple iframe widget: http://my-great-widget.com/widgwt' width="100" height="100"
frameborder='0'>
frameborder=’0′ is used to make sure the ifrmae doesn’t have a border
so it looks more natural on the page. The
http://my-great-widget.com/widget is responsible of serving the widget
content as a complete HTML page.
Inline gadgets might look like this:
function createMyWidgetHtml() { return "Hello world of widgets"; }
document.getElementById('myWidget').innerHTML = createMyWidgetHtml();
As you can see, the function createMyWidgetHtml() it responsible for
creating the actual widget content and does not necessarily have to
talk to a server to do that. In the iframe example there must be a
server. In the inline example there does not need to be a server,
although if needed, it’s possible to get data from the server, which
actually is a very common case, widgets typically do call server side
code. Using the inline method server side code is invoked by means of
on-demmand javascript.
So, to summarize, in the iframe case we simply place an iframe HTML
code and point the source of the iframe to a sever location which
actually serves the content of the widget. In the inline case we
create the content locally using javascript. You may of course combine
usage of iframe with javascript as well as use of the inline method
with server side calls, you’re not restricted by that, but the paths
start differentially.
So what is the big deal? What’s the difference? There are several
important differences, so here starts the interesting part of the
post.
Security. iFrame widgets are more secure.
What risks do gadgets impose and who’s actually being put at risk? The
user of the site and the site’s reputation are at risk.
With inline gadgets the browser thinks that the source of the gadget
code code comes from the hosting site. Let’s assume you’re browsing
your favorite mail application http://my-wonderful-email.com and this
mail application has installed a widget that displays a clock from
http://great-clock-widgets.com/. If that widgets is implemented as an
inline widget the browser thinks that the widget’s code originated at
my-wonderful-email.com and not at great-clock-widgets.com and so it’ll
let the widget’s code ultimately get access to the cookies owned by
my-wonderful-email.com and the widget’s evil author will steal your
email. It’s important to realize that browsers don’t care about where
the javascript file is hosted; as long as the code runs on the same
frame, the browser regards all code as originationg at the frame’s
domain. So, you as a user get hurt by losing control over your email
account and my-wonderful-email gets hurt by losing its reputation.
If the same clock would have gotten implemented inside an iframe and
the iframe source is different from the page source (which is the
common case, e.g. the page source is my-wonderful-email.com and the
gadget source is great-clock-widgets.com) then the browser would not
allow the clock widgets access to the page cookies, nor will it allow
access to any other part of the hosting document, including the host
page dom. That’s way more secure. As a matter of fact, personal home
pages such as iGoogle don’t even allow inline gadgets, only iframe
gadgets are allowed. (inline gadgets are allowed only in rare cases,
only after thorough inspection by the iGoogle team to make sure
they’re not malicious)
To sum up, iframe widgets are way more secure. However, they are also
way more limited in functionality. Next we’ll discuss what you lose in
functionality.
Look and feel In the look and feel battle inline gadgets (usually**)
win. The nice thing about them is that they can be made to look as
part of the page. They can inherit CSS styles from the page, including
fonts, colors, text size etc. Iframes, OTHO must define their CSS from
the grounds up so it’s pretty hard for them to blend nicely in the
page.
But what’s even more important is that iframes must declare what their
size is going to be. When adding an iframe to a page you must include
a width and a height property and if you don’t, the browser will use
some default settings. Now, if your widget is a clock widget that’s
easy enough b/c you know exacly what size you want it to be, but in
many cases you don’t know ahead of time how much space your widget is
going to take. If, for example you’re authoring a widget that displays
a list of some sort and you don’t know how long this list is going to
be or how wide each item is going to be. Usually in HTML this is not a
big deal because HTML is a declarative based language so all you need
to do is tell the browser what you want to display and the browser
will figure out a reasonable layout for it, however with iframe this
is not the case; with ifrmaes browsers demand that you tell it exactly
what the iframe size is and it will not figure it out by itself. This
is a real problem for widget authors that want to use iframes – if you
require too much space the page will have voids in it and if you
specify too little the page will have scrollbars in it, god forbids.
Look and feel wise, inline wins. But note that this really depends on
your widget application. If all you want to do is a clock, you may get
along with an iframe just as well.
Server side vs. Client side IFrmaes require you specify a src URL so
when implementing a widget using an iframe you must have server side
code. This could both be a limitation and a headache to some (owning a
server, domain name etc, dealing with load, paying network bills etc)
but to others this is actually a point in favor of iframes b/c it
let’s you completely write your widgets in server side technologies,
so you can write a lot of the code and actually almost all of it using
your favorite server side technology whether it be asp.net, django,
ror, jsp, struts , perl or other dinosaurs. When implementing an
inline gadget you’ll find yourself more and more practicing your
javascript Ninja.
What’s the decision algorithm then? Widget authors: If the widget can
be implemented as an iframe, prefer an Iframe simply for preserving
users security and trust. If a widget requires inlining (and the
medium allows that, e.g. not iGoogle and friends) use inline but dare
not exploit users trust!
Widget installers: When installing a widget in your blog you don’t see
a “safe for users” ribbon on the widgets. How can you tell if the
widget is safe or not? There are two alternatives I can suggest: 1)
trust the vendor 2) read the code. Either you trust the widget
provider and install it anyway or you take the time to read its code
and determine yourself whether it’s trustworthy or not. Reality is
that most site owners don’t bother reading code or are not even aware
of the risk they’re putting their users at, and so widget providers
are blindly trusted. In many cases this is not an issue since blogs
don’t usually hold personal information about their readers. I suspect
things will start changing once there are few high profile exploits
(and I hope it’ll never get to it).
Users: Usres are kept in the dark. Just as there are no “safe for
users” ribbons on widgets site owners install, there are no “safe to
use” sites and basically users are kept in the dark and have no idea,
even if they have the technical skills, whether or not the site they
are using contains widgets, whether the widgets are inline or not and
whether they are malicious. Although in theory a trained developer can
inspect the code up-front, before running it in her browser and losing
her email account to a hacker, however this is not practical and there
should be no expectation that users en mass will do that. IMO this is
an unfortunate condition and I only hope attackers will not find a way
of taking advantage of that and doom the wonderful open widget culture
on the web.
Happy widgeting folks!
Some blog platforms have a somewhat different structures for widgets and they may sometimes have both widgets and plugins that may
correlate in their functionality, but for the matter of the discussion
here I’ll lously use the term widget to discuss the “raw” type which
consists of client side javascript code
** Although in most cases you’d want widgets to inherit styles from the hosting page to make them look consistent with it, sometimes you
actually don’t want the widget to inherit styles from the page, so in
this case iFrames let you start your CSS from scratch.

Why not doing both ?
I prefer to offer third party sites a script like:
<script type="text/javascript" src="urlToYourScript"></script>
the file on your server looks like :
document.writeln('<iframe src="pathToYourWidget"
name="MagicIframe" width="300" height="600" align="left" scrolling="no"
marginheight="0" marginwidth="0" frameborder="0"></iframe>');
UPDATE:
one disadvantage of using an iframe that points to an url on your server is that you do not generate a "real" backlink if someone clicks on an url from your server pointing to your server.

I'm sure many developers/site owners would appreciate a Javascript solution that they can style to their needs rather than using an iframe. If I was going to include a component from a third party, I would rather do it via Javascript because I would have more control.
As far as ease of use, both are similar in simplicity, so no real tradeoff there.
One other thought, make sure you get a SSL cert for whatever domain you're hosting this on and write out the include statement accordingly if the page is served over SSL. In case your site owners have a reason for using SSL, they would surely appreciate this, because Firefox and other browsers will complain when a page is served with a mix of secure/insecure content.

If the widget can be embedded in an iframe, it will be better for the frontend performance of the hosting site as iframes do not block content download. However, as others have commented there are other drawbacks to using iframes.
If you do implement in javascript, please consider frontend performance best practices when developing. In particular, you should look at Non blocking javascript loading. Google analytics and other 3rd party widget providers support this method of loading. It would also help if you can load the javascript at the bottom of the page.

Nice to know that it's not to be deployed in a social networking site... that merely leaves the rest of the web ;-)
What would be most useful depends on your widget. IFrames and javascript generally serve quite different purposes, and can be mixed (i.e. javascript inside an iframe, or javascript creating an iframe).
IFrames got sizing issues; if it's supposed to be an exact fit to the page, do you know that it renders the same on all browsers, the data won't overflow it's container etc?
IFrames are simple. They can be a simple, static HTML-page.
When using IFrames, you expose your widget quite plainly.
But then again, why not have your third party site simply include the HMTL at a given url? The HTML can then be extended to contain javascript when/if you need it.
Pure Javascript allows for more flexibility but at the cost of some complexity.

The big plus of iframes: all CSS and JS is separated from the host page, so your existing CSS just works. (If you want the host site to style your content to fit in, that's a minus of course.)
The big minus of iframes: they have a fixed width and height and scroll-bars will appear if your content is larger.

Related

What is the best re-usable solution for serving complex content (think an entire tree of web pages) from one web app to another website?

Our goal is to let a person, similarly to how you can embed a youtube video, embed a tree of web pages on our SaaS into their own site.
The solution should be good looking, cross-browser, responsive and simple for the end user (ideally, should be search-bot friendly as well).
We are considering two primary options where the customer only needs to copy+paste a code snippet which supports embedding in a portion of the page (ex: the middle column) or full width (ex: everything under a header):
IFRAME: Let the user embed an iframe inside a div, together with a snippet of JS that would resize the iframe as the window is resized.
JS "APP": Let the user paste in a script tag to a JS script/app which would communicate cross-domain (via CORS or JSONP) with our servers.
Ideally, we would like to be able to launch full screen modals from our content.
Questions/concerns for:
IFRAME:
Can an iframe reliably update the URL of the parent’s browser window?
Can we reliably launch full screen modals from an iframe?
Can we reliably get the iframe to resize when the window is resized or iframe content changes?
JS "APP":
How significant is the overhead of dealing with properly encapsulating our app to avoid naming/library conflicts? For example, we will ideally stick to vanilla JS but if we want to use a library like Ember and a customer of ours has an Ember site.
Any non-obvious cross domain gotchas? We will be using CORS or JSONP.
We would like input on both the:
technical limitations of what’s possible to do
practical hurdles we’d have to overcome going down each path.
p.s. We’re also considering a back-up option, which is to “fake” integration, where we host the content on our site with a subdomain URL (similarly to how Tumblr lets people host their blog on something like “apple.tumblr.com”). If we go down this path we imagine letting the user theme the subdomain. We understand the pros and cons of this path. Downsides are, it’s more work for the user, and they need to keep two different sites in sync visually.
I think the best approach is to use the same approach Google and other big companies have been using for quite some time, the embedded script. It is way better looking and semantically unharmful (as an iframe could - arguably - be), and super cross-browser and simple, in fact, just as cross-browser and simple as the code that will be pushed (it can be recommended to be put in a <script async> tag, which will eliminate the need for a crafted async script and, though it won't be as full compatible, it degrades okay and will work very well on most cases).
As to the CORS, if basic cautions are taken, there's no need to worry a lot about it. I would say, though, that if you're planning to do something in Ember or Angular to be embedded, that may be a whole load of scripts/bytes that can even slow down the site/app and impact on the whole user experience, perhaps too much for a component that would be loaded like that. So whenever possible, vanilla JS should always be used in components, especially if Ember/Angular is used because of specific features like binding (specific vanilla JS codes can cover that with much less weight).

Ok to launch a full screen iframe widget? Vs. embedded?

I am needing to a custom widget into users of my applications websites and the initial thought it that an iframe would make it SO much simpler for a few reasons:
I can use the custom framework built for the application which provides a ton of pre-built code and features that i'll be using in the widget and thus wouldn't have to recreate. Cross browser event handlers and prototyped objects are just a few of many examples.
I don't have to worry about clashing with CSS and more specifically
won't have to use inline css for every dom element I create.
Cross domain requests are not a problem because i've already built
the functionality for everything that needs to be communicated using
jsonp, so don't let that be a downside for an embedded dom widget.
The idea as of right now is to write a quick javascript snippet that is essentially a button and loads a transparent iframe above the window that is full screen. This will give me control of the entire view and also allow me to write the widget just like I would any other part of the parent application. Maintaining the same json communication, using the same styles, using the framework etc. Clicking on any part of the iframe that was is not part of the widget (which will likely load centered in the middle of the screen, and be full screen if on a mobile device) will dismiss the widget and resume the user back to their normal navigation within the website. However, they can interact with my widget while its up, just like it were an embedded portion of the website that happened to load a javascript popup.
The widget itself does communication somewhat heavily with the server. There is a few requests on load, and then as the user interacts, it typically sends a request, changes the view and then wait for another response.
All that being said, is this a bad idea, or otherwise unprofessional idea? Should I put the extra work into embedding the widget directly into the hosts DOM and rewrite all the convenient framework code? I don't have a problem doing that, but if an iframe is a more appropriate choice, then I think i'd rather that. My only limitation is I need to support down to IE8, and of course, the widget needs to be viewable on both desktop and mobile, and the widget cannot be obtrusive to the clients website.
Some good reading from another post. Although closed, it poses some decent arguments in favor of iframes.
Why developers hate iframes?
A few points that resonate well:
Gmail, live.com, Facebook any MANY other major websites on the
internet take advantage iframes and in situations where they are
used properly...well that is what they were made for.
In situations especially like mine its considered a better practice
to prevent any possible compatibility issues with a remote website I
have no control over. Would I rather use an iframe, or destroy a
persons website? Sure I can take all possible precautions, and the
likelyhood of actually causing problems on another persons site is
slim, but with an iframe its impossible. Hence why they were created
in the first place.
SEO in my situation does not matter. I am simply extending a
javascript application onto remote users websites, not providing
searchable content.
For the above reasons, I think that taking the easier approach is actually the more professional option. Iframes in general have a bit of a misconception, I think because of their overuse in ugly ways in the past, but then again tables also have that same misconception yet believe it or not, when data is best displayed in a tabular fashion, it makes sense to use...wait for it...tables. Though we do this behind css values such as display: table-cell.
For now iframes get my vote. I'll update this answer if a little further down the development road on this project, I change my mind.

what is better? using iframe or something like jquery to load an html file in external website

I want my customers create their own HTML on my web application and copy and paste my code to their website to showing the result in the position with customized size and another options in page that they want. the output HTML of my web application contain HTML tags and JavaScript codes (for example is a web chart that created with javascript).
I found two way for this. one using iframe and two using jquery .load().
What is better and safer? Is there any other way?
iframe is better - if you are running Javascript then that script shouldn't execute in the same context as your user's sites: you are asking for a level of trust here that the user shouldn't need to accede to, and your code is all nicely sandboxed so you don't have to worry about the parent document's styles and scripts.
As a front-end web developer and webmaster I've often taken the decision myself to sandbox third-party code in iframes. Below are some of the reasons I've done so:
Script would play with the DOM of the document. Once a third-party widget took it upon itself to introduce buggy and performance-intensive PNG fix hacks for IE across every PNG used in img tags and CSS across our site.
Many scripts overwrite the global onload event, robbing other scripts of their initialisation trigger.
Reading local session info and sending it back to their own repositories.
Loading any number of resources and perform CPU-intensive processes, interrupting and weighing down my site's core experience.
The above are all examples of short-sightedness or malice on the part of the third parties you may see yourself as above, but the point is that as one of your service's users I shouldn't need to take a gamble. If I put your code in an iframe, I know it can happily do its own thing and not screw with my site or its users. I can also choose to delay load and execution to a moment of my choosing (by dynamically loading the iframe at a moment of choice).
To argue the point in terms of your convenience rather than the users':
You don't have to worry about any of the trust issues associated with XSS. You can honestly tell your users they're not exposing themselves to any unnecessary worry by running your tool.
You don't have to make the extra effort to circumvent the effects of CSS and JS on your users' sites.

Make programming langugage for your web app in JS that compiles to JS w/ PHP to ensure thorough filtering of user-uploaded html5 canvas animations?

A persistent follow-up of an admittedly similar question I had asked: What security restrictions should be implemented in allowing a user to upload a Javascript file that directs canvas animation?
I like to think I know JS decent enough, and I see common characters in all the XSS examples I've come accoss, which I am somewhat familiar with. I am lacking good XSS examples that could bypass a securely sound, rationally programmed system. I want people to upload html5 canvas creations onto my site. Any sites like this yet? People get scared about this all the time it seems, but what if you just wanted to do it for fun for yourself and if something happens to the server then oh well it's just an animation site and information is spread around like wildfire anyway so if anyone cares then i'll tell them not to sign up.
If I allow a single textarea form field to act as an IDE using JS for my programming language written in JS, and do string replacing, filtering, and validation of the user's syntax before finally compiling it into JS to be echoed by PHP, how bad could it get for me to host that content? Please show me how you could bypass all of my combined considerations, with also taking into account the server-side as well:
If JavaScript is disabled, preventing any POST from getting through, keeping constant track of user session.
Namespacing the Class, so they can only prefix their functions and methods with EXAMPLE.
Making instance
Storing my JS Framework in an external (immutable in the browser?) JS file, which needs to be at the top of the page for the single textarea field in the form to be accepted, as well as a server-generated key which must follow it. On the page that hosts the compiled user-uploaded canvas game/animation (1 per page ONLY), the server will verify the correct JS filename string before echoing the rest out.
No external script calls! String replacing on client and server.
Allowing ONLY alphanumeric characters, dashes and astericks.
Removing alert, eval, window, XMLHttpRequest, prototyping, cookie, obvious stuff. No native JS reserved words or syntax.
Obfuscating and minifying another external JS file that helps to serve the IDE and recognize the programming language's uniquely named Canvas API methods.
When Window unloads, store the external JS code in to two dynamically generated form fields to be checked by the server in POST. All the original code will be cataloged in the DB thoroughly for filtering purposes.
Strict variable naming conventions ('example-square1-lengthPROPERTY', 'example-circle-spinMETHOD')
Copy/Paste Disabled, setInterval to constantly check if enabled by the user. If so, then trigger a block to the database, change window.location immediately and check the session ID through POST to confirm in case JS becomes disabled between that timeframe.
I mean, can I do it then? How can one do harm if they can't use HEX or ASCII and stuff like that?
I think there are a few other options.
Good places to go for real-life XSS tests, by the way, are the XSS Cheat Sheet and HTML5 Security Cheetsheet (newer). The problem with that, however, is that you want to allow Javascript but disallow bad Javascript. This is a different, and more complex, goal than the usual way of preventing XSS, by preventing all scripts.
Hosting on a separate domain
I've seen this referred to as an "iframe jail".
The goal with XSS attacks is to be able to run code in the same context as your site - that is, on the same domain. This is because the code will be able to read and set cookies for that domain, intiate user actions or redress your design, redirect, and so forth.
If, however, you have two separate domains - one for your site, and another which only hosts the untrusted, user-uploaded content, then that content will be isolated from your main site. You could include it in an iframe, and yet it would have no access to the cookies from your site, no access to redress or alter the design or links outside its iframe, and no access to the scripting variables of your main window (since it is on a different domain).
It could, of course, set cookies as much as it likes, and even read back the ones that it set. But these would still be isolated from the cookies for your site. It would not be able to affect or read your main site's cookies. It could also include other code which could annoy/harrass the user, such as pop-up windows, or could attempt to phish (you'd need to make it visually clear in your out-of-iframe UI that the content served is not part of your site). However, this is still sandboxed from your main site, where you own personal payload - your session cookies and the integrity of your overarching page design and scripts, is preserved. It would carry no less but no more risk than any site on the internet that you could embed in an iframe.
Using a subset of Javascript
Subsets of Javascript have been proposed, which provide compartmentalisation for scripts - the ability to load untrusted code and have it not able to alter or access other code if you don't give it the scope to do so.
Look into things like Google CAJA - whose aim is to enable exactly the type of service that you've described:
Caja allows websites to safely embed DHTML web applications from third parties, and enables rich interaction between the embedding page and the embedded applications. It uses an object-capability security model to allow for a wide range of flexible security policies, so that the containing page can effectively control the embedded applications' use of user data and to allow gadgets to prevent interference between gadgets' UI elements.
One issue here is that people submitting code would have to program it using the CAJA API. It's still valid Javascript, but it won't have access to the browser DOM, as CAJA's API mediates access. This would make it difficult for your users to port some existing code. There is also a compilation phase. Since Javascript is not a secure language, there is no way to ensure code cannot access your DOM or other global variables without running it through a parser, so that's what CAJA does - it compiles it from Javascript input to Javascript output, enforcing its security model.
htmlprufier consists of thousands of regular expressions that attempt "purify" html into a safe subset that is immune to xss. This project is bypassesed very few months, because it isn't nearly complex enough to address the problem of XSS.
Do you understand the complexity of XSS?
Do you know that javascript can exist without letters or numbers?
Okay, they very first thing I would try is inserting a meta tag that changes the encoding to I don't know lets say UTF-7 which is rendered by IE. Within this utf-7 enocded html it will contain javascript. Did you think of that? Well guess what there is somewhere between a hundred thousand and a a few million other vectors I didn't think of.
The XSS cheat sheet is so old my grandparents are immune to it. Here is a more up to date version.
(Oah and by the way you will be hacked because what you are trying to do fundamentally insecure.)

Best practices for providing dynamic content 'drop in' widgets for third party websites?

I am wondering what best practices are for providing dynamic content in lightweight, 'drop in' widget style that can be used by third party content editors.
To elaborate, we would like to give third parties the ability to show dynamic content from us on their website without a back end system integration where they would have to call one of our APIs server side - ideally it would be possible for their content editors simply to include a provided snippit in their HTML. A concrete example would be a bestseller list that changes every few hours.
Using an IFRAME is one obvious way of accomplishing this, but I'm curious if there are others that allow tighter integration into their source and more flexible styling and are 'expected best practice' for such an offering as it isn't a field I know well - JavaScript/JSON perhaps?
I'd call an iframe best practice since it does not grant the framed content any excess rights, but having a JavaScript file that other sites can include seems pretty common as well, so you could probably get a lot of site owners to accept that. Still, the iframe is preferable, you shouldn't use JavaScript unless it really makes a difference.
You can easily make the to-be-iframed page configurable through parameters in the link, so site owners can set things like background and font to match their own site.
Alternative to iFrames: JSONP
JSONP is used by Javascript widget libraries to pull in data from the widget library's server since JSONP gets around the same-origin issues.
This enables your JS widget library to provide data and UI services to the hosting page without any changes to the hosting page's server.
It's clean, neat, and avoids various iframe issues.
As mentioned in other answers, anyone including your JS in their pages is trusting that your JS is not a security/privacy issue. But that's not a problem depending on your relationship with the folks who'd include your library.
Be aware that you're opening a potential security Pandora's box. Take a look at the Caja project, it allows to safely embed untrusted JavaScript content.

Categories