0

Right now I'm running getting a local template URL and creating a div to insert it into.

Inside of my template is a simple <h3>Hello World</h3>

var newDiv = document.createElement('div');
const template = chrome.runtime.getURL("template.html");

How can I insert the contents of template into my newDiv.innerHTML?

Zack Shapiro
  • 6,648
  • 17
  • 83
  • 151
  • You can edit the innerHTML of any element like so: `.innerHTML = `. In your case this would be `newDiv.innerHTML = template`. – itzFlubby Jan 03 '20 at 20:08
  • Right, but `template` is a file path string, not the actual contents of that file that I could shove into the `innerHTML` – Zack Shapiro Jan 03 '20 at 20:09
  • Ah ok. I see. Sorry! What you are trying to do is done via an XMLHttpRequest. Have a look at [this](https://stackoverflow.com/questions/10642289/return-html-content-as-a-string-given-url-javascript-function) – itzFlubby Jan 03 '20 at 20:11

1 Answers1

0

You can add HTML content to an element using element.innerHTML = ....
You can get the template content by using a XMLHttpRequest.

Have a look at this:

function getTemplate(url, success) {
    var request = new XMLHttpRequest();
    request.onreadystatechange = function() {

        // If the request doesn't have an error status code,
        // the contents of the loaded URL (request.responseText) are sent
        // to the callback function (success).

        if (request.readyState === 4 && request.status === 200) 
            success(request.responseText);
    }
    request.open("GET", url, false);
    request.send();
}

You can use the function like shown in the code below. It uses a callback function for the success argument, which you have to specify.

getTemplate(url, function(responseText) {
    document.write(responseText);
    // or add the responseText to your div with: yourDiv.innerHTML += responseText;
});

Note that the request will mostly fail when you try to load content from a different origin (like a different file on your computer, or when you try to load site A's content from a script on site B).

Sacha
  • 819
  • 9
  • 27