Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read data in HTML object tag

I have a text file stored on the server and an object in HTML like this:

<object id="data" type="text/plain" data="test.txt"></object>

How can I read the contents of test.txt in Javascript? What I have so far is:

var data = document.getElementByID("data");

But I can't figure out how to read the HTML document inside the object tag.

like image 339
rhynodegreat Avatar asked Apr 16 '16 01:04

rhynodegreat


1 Answers

The object tag has to make a separate request to the server and then load that content. Meanwhile, your JavaScript has already executed and "misses the bus."

Run your code inside the onload event of the object.

Then use .contentDocument.body.childNodes[0].innerHTML to view the text file.

var object = document.getElementById("data");
object.onload = function() {
    var data = object.contentDocument.body.childNodes[0].innerHTML;
    // use the data
};
like image 144
4castle Avatar answered Oct 12 '22 01:10

4castle