Desde object hasta iframe - otras tecnologías de incrustación

Esta traducción está incompleta. Por favor, ayuda a traducir este artículo del inglés.

Ahora ya deberías estar acostumbrado a integrar cosas en tus páginas web, incluyendo imágenes, video y audio. En este punto nos gustaría que des algo así como un paso al costado, prestando atención a elementos que te permiten integrar una amplia variedad de tipos de contenido en tus páginas web: los elementos <iframe>, <embed> y <object>. Los <iframe>s son para incrustar otras páginas web, y los otros dos te permiten incrustar PDFs, SVG e incluso Flash — una tecnología que está en su camino de despedida, pero la cual seguirás viendo semi-regularmente.

Prerrequisitos: Conocimientos básicos de informática, software básico instalado, conocimientos básicos de  manejo de archivos, familiaridad con los fundamentos de HTML (visto en Iniciando en HTML) y los artículos previos en este modulo.
Objetivo: To learn how to embed items into web pages using <object><embed>, and <iframe>, like Flash movies and other webpages.

Hace mucho tiempo en la Web, era popular usar marcos para crear sitios web, pequeñas partes de un sitio web almacenadas en páginas HTML individuales. Estos estaban incrustados en un documento maestro llamado conjunto de marcos , que le permitía especificar el área en la pantalla que ocupaba cada cuadro, como el tamaño de las columnas y las filas de una tabla. Estos fueron considerados el colmo del frescor a mediados y finales de los 90, y había evidencia de que tener una página web dividida en trozos más pequeños como este era mejor para velocidades de descarga, especialmente notable con conexiones de red tan lentas en ese momento. Sin embargo, tuvieron muchos problemas, que superaron con creces cualquier aspecto positivo ya que las velocidades de red se hicieron más rápidas, por lo que ya no se ve que se usen.

Poco tiempo después (finales de los 90, principios de 2000), las tecnologías de complementos se volvieron muy populares, como los Applets de Java y Flash . Esto permitió a los desarrolladores web incorporar contenido enriquecido en páginas web como videos y animaciones, que simplemente no estaban disponibles solo a través de HTML. . La incrustación de estas tecnologías se logró a través de elementos como <object> y el <embed> menos utilizado, y fueron muy útiles en ese momento. Desde entonces, pasaron de moda debido a muchos problemas, incluidos el acceso, la seguridad, el tamaño del archivo y más; en la actualidad, la mayoría de los dispositivos móviles ya no son compatibles con estos complementos, y el soporte de escritorio está en camino de desaparecer.

Finalmente, apareció el elemento <iframe> (junto con otras formas de incrustación de contenido, como <canvas> , <video> , etc.). Esto proporciona una forma de insertar un documento web entero dentro de otro, como si fuera un <img> u otro elemento similar, y se usa regularmente hoy.

Con la lección de historia fuera del camino, sigamos y veamos cómo usar algunos de estos.

 

Aprendizaje activo: usos de incrustación clásicos

En este artículo vamos a ir directamente a una sección de aprendizaje activo, para darle una idea real de las tecnologías de inclusión que son útiles. El mundo en línea está muy familiarizado con Youtube , pero muchas personas no conocen algunas de las instalaciones para compartir que tiene disponibles. Veamos cómo Youtube nos permite insertar un video en cualquier página que nos guste usando un <iframe> .

  1. Primero, ve a Youtube y encuentra el video que te gusta.
  2. Debajo del video, encontrará un botón Compartir : seleccione esto para mostrar las opciones para compartir.
  3. Seleccione el botón Insertar y recibirá un código <iframe> - copie esto.
  4. Insértelo en el cuadro de entrada a continuación, y vea cuál es el resultado en la salida .

Para obtener puntos de bonificación, también puede intentar insertar un mapa de Google en el ejemplo:

  1. Ve a Google Maps y encuentra un mapa que te guste.
  2. Haga clic en el "Menú Hamburger" (tres líneas horizontales) en la esquina superior izquierda de la IU.
  3. Seleccione la opción Compartir o Insertar mapa .
  4. Seleccione la opción Insertar mapa, que le dará un código <iframe> - copie esto.
  5. Insértelo en el cuadro de entrada a continuación, y vea cuál es el resultado en la salida .

Si comete un error, siempre puede restablecerlo usando el botón Restablecer . Si realmente te quedas atascado, presiona el botón Mostrar solución para ver una respuesta.

 

Iframes in detail

So, that was easy and fun right? <iframe> elements are designed to allow you to embed other web documents into the current document. This is great for incorporating third party content into your website that you might not have direct control over and don't want to have to implement your own version of — such as video from online video providers, commenting systems like Disqus, maps from online map providers, advertising banners, etc. The live editable examples you've been using through this course are implemented using <iframe>s.

There are some serious Security concerns to consider with <iframe>s, as we'll discuss below, but this doesn't mean that you shouldn't use them in your websites — it just requires some knowledge and careful thinking. Let's explore the code in a bit more detail. Say you wanted to include the MDN glossary on one of your webpages — you could try something like this:

<iframe src="https://developer.mozilla.org/en-US/docs/Glossary"
        width="100%" height="500" frameborder="0"
        allowfullscreen sandbox>
  <p> <a href="https://developer.mozilla.org/en-US/docs/Glossary">
    Fallback link for browsers that don't support iframes
  </a> </p>
</iframe>

This example includes the basic essentials needed to use an <iframe>:

allowfullscreen
If set, the <iframe> is able to be placed in fullscreen mode using the Full Screen API (somewhat beyond scope for this article.)
frameborder
If set to 1, this tells the browser to draw a border between this frame and other frames, which is the default behaviour. 0 removes the border. Using this isn't really recommended any more, as the same effect can be better achieved using border: none; in your CSS.
src
This attribute, as with <video>/<img>, contains a path pointing to the URL of the document to be embedded.
width and height
These attributes specify the width and height you want the iframe to be.
Fallback content
In the same way as other similar elements like <video>, you can include fallback content between the opening and closing <iframe></iframe> tags that will appear if the browser doesn't support the <iframe>. In this case we have included a link to the page instead. It is unlikely that you'll come across any browser that doesn't support <iframe>s these days.
sandbox
This attribute, which works in slightly more modern browsers than the rest of the <iframe> features (e.g. IE 10 and above) requests heightened security settings; we'll say more about this in the next section.

Note: In order to improve speed, it's a good idea to set the iframe's src attribute with JavaScript after the main content is done loading. This makes your page usable sooner and decreases your official page load time (an important SEO metric.)

Security concerns

Above we mentioned security concerns — let's go into this in a bit more detail now. We are not expecting you to understand all of this content perfectly the first time; we just want to make you aware of this concern, and provide a reference to come back to as you get more experienced and start considering using <iframe>s in your experiments and work. Also, there is no need to be scared and not use <iframe>s — you just need to be careful. Read on...

Browser makers and Web developers have learned the hard way that iframes are a common target (official term: attack vector) for bad people on the Web (often termed hackers, or more accurately, crackers) to attack if they are trying to maliciously modify your webpage, or trick people into doing something they don't want to do, such as reveal sensitive information like usernames and passwords. Because of this, spec engineers and browser developers have developed various security mechanisms for making <iframe>s more secure, and there are also best practices to consider — we'll cover some of these below.

Clickjacking is one kind of common iframe attack where hackers embed an invisible iframe into your document (or embed your document into their own malicious website) and use it to capture users' interactions. This is a common way to mislead users or steal sensitive data.

A quick example first though — try loading the previous example we showed above into your browser — you can find it live on Github (see the source code too.) You won't actually see anything displayed on the page, and if you look at the Console in the browser developer tools, you'll see a message telling you why. In Firefox, you'll get told Load denied by X-Frame-Options: https://developer.mozilla.org/en-US/docs/Glossary does not permit framing. This is because the developers that built MDN have included a setting on the server that serves the website pages to disallow them from being embedded inside <iframe>s (see Configure CSP directives, below.) This makes sense — an entire MDN page doesn't really make sense to be embedded in other pages, unless you want to do something like embed them on your site and claim them as your own — or attempt to steal data via clickjacking, which are both really bad things to do. Plus if everybody started to do this, all the additional bandwidth would start to cost Mozilla a lot of money.

Only embed when necessary

Sometimes it makes sense to embed third party content — like youtube videos and maps — but you can save yourself a lot of headaches if you only embed third party content when completely necessary. A good rule of thumb for web security is "You can never be too cautious. If you made it, double-check it anyway. If someone else made it, assume it's dangerous until proven otherwise."

Besides security, you should also be aware of intellectual property issues. Most content is copyrighted, offline and online, even content you might not expect (for example, most images on Wikimedia Commons). Never display content on your webpage unless you own it or the owners have given you written, unequivocal permission. Penalties for copyright infringement are severe. Again, you can never be too cautious.

If the content is licensed, you must obey the license terms. For example, the content on MDN is licensed under CC-BY-SA. That means, you must credit us properly when you quote our content, even if you make substantial changes.

Use HTTPS

HTTPS is the encrypted version of HTTP. You should serve your websites using HTTPS whenever possible:

  1. HTTPS reduces the chance that remote content has been tampered with in transit,
  2. HTTPS prevents embedded content from accessing content in your parent document, and vice versa.

Using HTTPS requires a security certificate, which can be expensive (although Let's Encrypt makes things easier) — if you can't get one, you may serve your parent document with HTTP. However, because of the second benefit of HTTPS above, no matter what the cost, you must never embed third-party content with HTTP. (In the best case scenario, your user's Web browser will give them a scary warning.) All reputable companies that make content available for embedding via an <iframe> will make it available via HTTPS — look at the URLs inside the <iframe> src attribute when you are embedding content from Google Maps or Youtube, for example.

Note: Github pages allows content to be served via HTTPS by default, so is useful for hosting content. If you are using different hosting and are not sure, ask your hosting provider about it.

Always use the sandbox attribute

You want to give attackers as little power as you can to do bad things on your website, therefore you should give embedded content only the permissions needed for doing its job. Of course, this applies to your own content, too. A container for code where it can be used appropriately — or for testing — but can't cause any harm to the rest of the codebase (either accidental or malicious) is called a sandbox.

Unsandboxed content can do way too much (executing JavaScript, submitting forms, popup windows, etc.) By default you should impose all available restrictions by using the sandbox attribute with no parameters, as shown in our previous example.

If absolutely required, you can add permissions back one by one (inside the sandbox="" attribute value) — see the sandbox reference entry for all the available options. One important note is that you should never add both allow-scripts and allow-same-origin to your sandbox attribute — in that case the embedded content could bypass the same origin security policy that stops sites from executing scripts, and use JavaScript to turn off sandboxing altogether.

Note: Sandboxing provides no protection if attackers can fool people into visiting malicious content directly (outside an iframe). If there's any chance that certain content may be malicious (e.g., user-generated content), please serve it from a different domain to your main site.

Configure CSP directives

CSP stands for content security policy, and provides a set of HTTP Headers (metadata sent along with your web pages when they are served from a web server) designed to improve the security of your HTML document. When it comes to securing <iframe>s, you can configure your server to send an appropriate X-Frame-Options  header. This can prevent other websites from embedding your content in their webpages (which would enable clickjacking and a host of other attacks), which is exactly what the MDN developers have done, as we saw earlier on.

Note: You can read Frederik Braun's post On the X-Frame-Options Security Header for more background information on this topic. Obviously, it's rather out of scope for a full explanation in this article.

The <embed> and <object> elements

The <embed> and <object> elements serve a different function to <iframe> — these elements are general purpose embedding tools for embedding multiple types of external content, which include plugin technologies like Java Applets and Flash, PDF (which can be shown in a browser with a PDF plugin), and even content like videos, SVG and images!

Note: A plugin is software that provides access to content the browser cannot read natively.

However, you are unlikely to use these elements very much — Applets haven't been used for years, Flash is no longer very popular, due to a number of reasons (see The case against plugins, below), PDFs tend to be be better linked to than embedded, and other content such as images and video have much better, easier elements to handle those. Plugins and these embedding methods are really a legacy technology, and we are mainly mentioning them in case you come across them in certain circumstances like intranets, or enterprise projects.

If you find yourself needing to embed plugin content, this is the kind of information you'll need, at a minimum:

  <embed> <object>
URL of the embedded content src data
accurate media type of the embedded content type type
height and width (in CSS pixels) of the box controlled by the plugin height
width
height
width
names and values, to feed the plugin as parameters ad hoc attributes with those names and values single-tag <param> elements, contained within <object>
independent HTML content as fallback for an unavailable resource not supported (<noembed> is obsolete) contained within <object>, after <param> elements

Note: <object> requires a data attribute, a type attribute, or both. If you use both, you may also use the typemustmatch attribute (only implemented in Firefox, as of this writing). typemustmatch keeps the embedded file from running unless the type attribute provides the correct media type. typemustmatch can therefore confer significant security benefits when you're embedding content from a different origin (it can keep attackers from running arbitrary scripts through the plugin).

Here's an example that uses the <embed> element to embed a Flash movie (see this live on Github, and check the source code too):

<embed src="whoosh.swf" quality="medium"
       bgcolor="#ffffff" width="550" height="400"
       name="whoosh" align="middle" allowScriptAccess="sameDomain"
       allowFullScreen="false" type="application/x-shockwave-flash"
       pluginspage="http://www.macromedia.com/go/getflashplayer">

Pretty horrible, isn't it. The HTML generated by the Adobe Flash tool tended to be even worse, using an <object> element with an <embed> element embedded in it, to cover all bases (check out an example.) Flash was even used successfully as fallback content for HTML5 video, for a time, but this is increasingly being seen as not necessary.

Now let's look at an <object> example that embeds a PDF into a page (see the live example and the source code):

<object data="mypdf.pdf" type="application/pdf"
        width="800" height="1200" typemustmatch>
  <p>You don't have a PDF plugin, but you can <a href="myfile.pdf">download the PDF file.</a></p>
</object>

PDFs were a necessary stepping stone between paper and digital, but they pose many accessibility challenges and can be hard to read on small screens. They do still tend to be popular in some circles, but it is much better to link to them so they can be downloaded or read on a separate page, rather than embedding them in a webpage.

The case against plugins

Once upon a time, plugins were indispensable on the Web. Remember the days when you had to install Adobe Flash Player just to watch a movie online? And then you constantly got annoying alerts about updating Flash Player and your Java Runtime Environment. Web technologies have since grown much more robust, and those days are over. For most applications, it's time to stop delivering content that depends on plugins, and start taking advantage of Web technologies instead.

  • Broaden your reach to everyone. Everyone has a browser, but plugins are increasingly rare, especially among mobile users. Since the Web is largely usable without plugins, people would rather just go to your competitors' websites than install a plugin.
  • Give yourself a break from the extra accessibility headaches that come with Flash and other plugins.
  • Stay clear of additional security hazards. Adobe Flash is notoriously insecure, even after countless patches. In 2015, Alex Stamos, chief security officer of Facebook, even requested that Adobe discontinue Flash.

So what should you do? If you need interactivity, HTML and JavaScript can readily get the job done for you with no need for Java applets or outdated ActiveX/BHO technology. Instead of relying on Adobe Flash, you can use HTML5 video for your media needs, SVG for vector graphics, and Canvas for complex images and animations. Peter Elst was already writing some years ago that Adobe Flash is rarely the right tool for the job, except for specialized gaming and business applications. As for ActiveX, even Microsoft's Edge browser no longer supports it.

Summary

The topic of embedding other content in web documents can quickly become very complex, so in this article we've tried to introduce it in a simple, familiar way that will immediately seem relevant, while still hinting at some of the more advanced features of the involved technologies. To start with, you are unlikely to use embedding for much beyond including third party content like maps and videos on your pages. As you become more experienced however, you are likely to start finding more uses for them.

There are many other technologies that involve embedding external content besides the ones we discussed here. We saw some in earlier articles, such as <video>, <audio>, and <img>, but there are others to discover, such as <canvas> for JavaScript-generated 2D and 3D graphics, and <svg> for embedding vector graphics. We'll look at SVG in the next article of the module.

 

In this module

 

Etiquetas y colaboradores del documento

Colaboradores en esta página: luchiano199, SphinxKnight, dylanroman03
Última actualización por: luchiano199,