Javascript load html code

How to Load HTML, CSS, and JS Code into an iFrame

If you’re just here for the answer, not the story, the solution is at the bottom. If you’ve ever used JSFiddle, Codepen, or others, this problem will be familiar to you: The goal is to take some HTML, CSS, and JS (stored as strings) and create an iframe with the code loaded inside. This problem should be easy, but it isn’t. At least. It wasn’t, until I found the golden ticket I had been waiting for all along. But more on that later. Let’s start with all the things that didn’t work, because that’s more fun.

Attempt #1: Using srcdoc

After doing a bit of research, I was thrilled to discover that it’s possible to add a srcdoc attribute to iframes. If you pass in an HTML string, the iframe will load with that HTML content inside:

 srcdoc="

This text will appear in the iframe!

"
>

1. Browser Support for srcdoc is not great

If we want to support IE or Edge, we’ll need a different approach (or a polyfill).

2. It’s possible to «escape» from CSS/JS

function setIframeContent(iframe,  html, css, js >)  const source = `  $css>  $html> $js>   ` iframe.srcdoc = source > 

The problem? When writing CSS or JS, it’s possible to «escape» out into HTML land, simply by including

or in the code, respectively. This bug is actually quite common; both JSFiddle and Codepen are affected:

Attempt #2: Serverless Boomerang

To fix the browser support issue, let’s replace srcdoc with a regular src attribute. In order to do this, we’ll need to pass a real URL instead of just code. Perhaps we can set up a page which takes HTML, CSS, and JS «GET» parameters and spits out the same type of page as before, but this time loaded from an actual URL. This is a perfect time to use a serverless architecture, because we just want a single endpoint that does one thing. Here’s my attempt:

module.exports = (req, res) =>  // Code comes from GET params in URL const  html = '', css = '', js = '' > = req.query // Generate and send HTML page return res.send(`  $css>  $html> $js>   `) > 
  1. «Escaping» from CSS/JS into HTML is still a problem
  2. The entire source code is passed in a URL, which isn’t ideal.

Attempt #3: Serverless Boomerang (redux)

Our first boomerang solved the browser support problem, but still has the «escaping» issue to deal with.

Fortunately, due to the way that we pass in the code, this can actually be solved. Rather than inserting the CSS and JS into the page on the server, we can do it on the client! This works because the URL GET parameters are still accessible to the client’s computer.

The source here is a bit longer, but it does work:

module.exports = (req, res) =>  return res.send(`     $req.query.html || ''>  `) > 

Now, if a script or style includes scary HTML characters, the browser will handle them for us when inserting said script/style into the document.

This solution is. fine. It works, technically. But we still have the soft URL length limit to consider. Plus, we’re now dealing with something server-side that feels like it should happen on the client.

There must be a better way.

Solution: Blob URLs

This entire time, we’ve been trying to simulate loading data from a URL:

  • First we used srcdoc to load data instead of loading from a URL
  • Then we used the boomerang to load code from a URL
  • Next we updated our boomerang to attempt to simulate the «loading CSS/JS from an external URL» behavior, despite every resource coming from one URL.

It turns out that Javascript has a feature to do just this: Blob URLs.

Blobs

We can use the Blob constructor to create a pseudo-file. It’s not a real file loaded from disk or from a URL — it’s just stored in memory. But in many ways, it functions just like a real loaded file.

Then, we can use URL.createObjectURL(blob) to create a URL that can be used to load the contents of the blob.

Here’s how that works in practice:

const getBlobURL = (code, type) =>  const blob = new Blob([code],  type >) return URL.createObjectURL(blob) > console.log(getBlobURL('

My webpage

', 'text/html')) // blob:https://dev.to/9ca05e31-05ea-48f8-838d-cc1ad0949ec8

Try running the above code in the console to see it for yourself! It will log a URL. If you paste the URL into a new tab (including the blob: bit at the beginning), it will load a page containing the HTML.

Notice the ‘text/html’ passed to getBlobURL ? We can change that too. Generating a CSS or JS blob is easy: Just pass text/css or text/javascript respectively.

Another benefit of blob URLs is that they stick around, and can be accessed any way that you would access a regular URL. Which means that we can actually load our CSS and JS files from a separate URL, so the «escaping» trick is no longer a problem.

Here’s a bare-bones implementation of this in practice:

const getGeneratedPageURL = ( html, css, js >) =>  const getBlobURL = (code, type) =>  const blob = new Blob([code],  type >) return URL.createObjectURL(blob) > const cssURL = getBlobURL(css, 'text/css') const jsURL = getBlobURL(js, 'text/javascript') const source = ` $css && `$cssURL>" />`> $js && ``> $html || ''>  ` return getBlobURL(source, 'text/html') > const url = getGeneratedPageURL( html: '

Hello, world!

', css: 'p ', js: 'console.log("hi")' >) const iframe = document.querySelector('#iframe') iframe.src = url

Oh, and browser support for Blob URLs is much better than srcdoc. 😉

The Moral?

Don’t fight the language, I guess.

I knew what I wanted to do: Load data from URLs. It just never occurred to me to look for a non-hacky way to do just that!

Источник

2 Ways To Add HTML Code In Javascript (A Quick Guide)

Welcome to a short beginner’s tutorial on how to add HTML code in Javascript. So you have finally gotten to the point of working with both HTML and Javascript, but the challenge is that you now have to add some HTML to an existing page.

Adding HTML code using Javascript is actually a simple “get target container and insert HTML” process:

  1. By directly changing or appending to the inner HTML.
    • var target = document.getElementById(«ID»);
    • target.innerHTML + ;
  2. By creating and inserting a new element.
    • var newElement = document.createElement(«p»);
    • newElement.innerHTML = «CONTENTS»;
    • document.getElementById(«ID»).appendChild(newElement);

Yep. As simple as this select-insert mechanism may seem like, there are actually quite a few ways to select and insert elements. So let us walk through some actual examples in this tutorial – Read on!

TLDR – QUICK SLIDES

How To Add HTML Code In Javascript

TABLE OF CONTENTS

WAYS TO ADD HTML CODE

All right, let us now move into the actual examples themselves – How we can work with Javascript to add HTML code and elements.

METHOD 1) DIRECTLY CHANGE HTML CODE

  
  • (A) First, we give the HTML element a unique id .
  • (B) Then select it with var ELEMENT = document.getElementById(ID) in Javascript.
  • (C & D) Finally, take note that innerHTML can be used in two directions.
    • var CONTENTS = ELEMENT.innerHTML to get the current contents.
    • ELEMENT.innerHTML = «FOO!» to replace the contents.
    • ELEMENT.innerHTML += «FOO!» to append to the existing contents.

    METHOD 2) CREATE & APPEND HTML ELEMENTS

      
    • (A & B) As usual, give the HTML element an id . Then use var PARENT = document.getElementById(«ID») to get it.
    • (C) But instead of directly replacing the innerHTML , we create a new HTML element instead.
      • We use var ELEMENT = document.createElement(«TAG») to create a new HTML tag.
      • Then change the contents using ELEMENT.innerHTML = «FOO» … Which you already know.
      • Finally, append the new element to the parent – PARENT.appendChild(ELEMENT) .

      MORE HTML SELECTION & INSERTION

      So far so good? Here are a few more examples of the various ways to select and insert HTML elements.

      GET HTML ELEMENTS IN JAVASCRIPT

        
      DemoD

      not John Wick.

      // (B) GET BY ID var demoA = document.getElementById("demoA"); console.log(demoA); //
      ] // (D) GET BY CSS CLASS var demoC = document.getElementsByClassName("demoC"); console.log(demoC); // html collection - [demoD] // (F) GET BY QUERY SELECTOR var demoE = document.querySelector("#demoE strong"); console.log(demoE); // not // (G) GET BY QUERY SELECTOR (MULTIPLE SELECTORS) var demoF = document.querySelectorAll("span.demoC, p#demoE"); console.log(demoF); // node list - [

      SET HTML/CSS PROPERTIES

        window.addEventListener("load", () => < // (A) GET HTML LIST var ul = document.getElementById("thelist"); // (B) DATA var data = ["Foo", "Bar", "Hello", "World", "John", "Doe"]; // (C) ADD LIST ITEMS for (let idx in data) < let li = document.createElement("li"); li.innerHTML = data[idx]; li.id = "item-" + idx; // set id li.style.color = "red"; // set style li.classList.add("dummy"); // add css class ul.appendChild(li); >>); 

      TAKE EXTRA NOTE OF THE LOADING ORDER!

        

      Lastly, this is a common pitfall among beginners – Not taking note of the order in which things are being loaded. Notice how demo is NULL in this example? Isn’t already defined!? Nope, Javascript is not broken. What happened is that HTML files load in a top-to-bottom, left-to-right manner.

      The is loaded first, and ran before is even rendered – This is how getElementById("demo") ends up as a NULL . To solve this problem, we can use window.addEventListener("load") (as in the previous example) to wait for the window to be fully loaded before proceeding with the scripts.

      DOWNLOAD & NOTES

      Here is the download link to the example code, so you don’t have to copy-paste everything.

      SUPPORT

      600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a "paid scripts and courses" business, so every little bit of support helps.

      EXAMPLE CODE DOWNLOAD

      Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

      That’s all for this guide, and here is a small section on some extras and links that may be useful to you.

      DIRECT HTML MANIPULATION VS CREATING OBJECTS

      • innerHTML works better when you are dealing with changing the text contents inside a single element.
      • createElement() makes more sense when you are dealing with lists and tables.

      So yep – It is up to you to decide which is more comfortable.

      TUTORIAL VIDEO

      INFOGRAPHIC CHEAT SHEET

      THE END

      Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

      Leave a Comment Cancel Reply

      Breakthrough Javascript

      Take pictures with the webcam, voice commands, video calls, GPS, NFC. Yes, all possible with Javascript - Check out Breakthrough Javascript!

      Socials

      About Me

      W.S. Toh is a senior web developer and SEO practitioner with over 20 years of experience. Graduated from the University of London. When not secretly being an evil tech ninja, he enjoys photography and working on DIY projects.

      Code Boxx participates in the eBay Partner Network, an affiliate program designed for sites to earn commission fees by linking to ebay.com. We also participate in affiliate programs with Bluehost, ShareASale, Clickbank, and other sites. We are compensated for referring traffic.

      Источник

      Читайте также:  Enable javascript local files
Оцените статью