0

In the object element with the ID x a text file is loaded and displayed correctly. How can I get this text with JavaScript?

I set

y.data = "prova.txt"

then tried

y.innerHTML;
y.text;
y.value;

None of these work.

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <object id="x" data="foo.txt"></object>
    <script>
      var y = document.getElementById("x")
    </script>
  </body>
</html>

Object element in HTML inspector

Sebastian Simon
  • 14,320
  • 6
  • 42
  • 61
  • 1
    Why did you expect `y.value` and `y.text` to work? Also, are you _only_ trying to get the text or do you really want to display the text on the page with an object element? There are better ways of doing both — with the same solution: AJAX. If so, this is an [XY problem](http://meta.stackexchange.com/questions/66377). – Sebastian Simon Aug 20 '15 at 12:35
  • i'm beginner, so i have tried these ways. Object loads correctly file text and show in browser ( iframe ? ), but all my attempt goes wrong –  Aug 20 '15 at 12:38
  • can you show a pratical example ? wiht XHR i have to enable Chrome plugins ... or change server setting Apache to load file; but i have saw in this way Chrome load CORS plugins –  Aug 20 '15 at 12:40
  • 2
    possible duplicate of [Javascript - read local text file](http://stackoverflow.com/questions/14446447/javascript-read-local-text-file) – Spencer Wieczorek Aug 20 '15 at 12:40
  • Not quite an exact duplicate unless Claudio is actually trying to use AJAX. – cjol Aug 20 '15 at 12:43
  • first attemps i have tried to use XHR and jquery get , to load file in browser, but need to enable CORS plugin or change apache setting; but in this way with object data ; text file is load correclty; browser display inner text; ISSUE why i can't access text inside object ? –  Aug 20 '15 at 12:47
  • 1
    @ClaudioDaffra please, try this in the browser's console. (to see if we're on the right path) `document.getElementById('x').contentDocument.getElementsByTagName('pre')[0].innerHTML`. I'm assuming you're running this example in a local server to avoid cross-site errors. – Jesús Otero Aug 20 '15 at 13:07
  • no right path gives me : Uncaught SyntaxError: Unexpected token ILLEGAL; –  Aug 20 '15 at 13:18
  • @ClaudioDaffra try the proposed solution in my updated answer. – Jesús Otero Aug 20 '15 at 13:34
  • 1
    You're getting the token ILLEGAL because StackOverflow is adding a fancy hidden unicode character in the innerHTML word, I suppose it's for security reasons. if you delete that part and retype, it will work just fine. – Jesús Otero Aug 20 '15 at 13:38
  • gives me this error : Uncaught SecurityError: Failed to read the 'contentDocument' property from 'HTMLObjectElement': Blocked a frame with origin "null" from accessing a frame with origin "null". Protocols, domains, and ports must match. –  Aug 20 '15 at 14:43
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/87503/discussion-between-claudio-daffra-and-jesus-otero). –  Aug 20 '15 at 15:03
  • 1
    Your problem is still due to cross-origin request problems (CORS) I'm afraid. I've updated my answer with an explanation and some possible suggestions to improve things. – cjol Aug 21 '15 at 13:44

3 Answers3

1

I'm afraid this isn't going to be easy as you'd like it to be.

According to your comments, you tried AJAX first, but came across CORS problems. This happens when you try to include data from files on a different domain name.

Since that didn't work, you tried to include the file inside an object tag. This works a bit like an iframe - the data will be displayed on the webpage, but for the same reasons as above, you cannot access the data through JavaScript if the file is under a different domain name. This is a security feature. That explains the error you were getting most recently:

Uncaught SecurityError: Failed to read the 'contentDocument' property from 'HTMLObjectElement'


Now, there are a few ways you might be able to get around this.

Firstly, if this is a program exclusively for your own use, you can start your browser with web-security disabled (though this is dangerous for browsing the web generally). In Chrome, for example, you can do this by launching Chrome with the --disable-web-security flag. More details here.

Secondly, you can try to arrange that your document and the file do belong under the same domain. You will probably only be able to do this if you have control of the file.

Your error message (specifically a frame with origin "null") makes me think that you are running the files directly in the web-browser rather than through a server. It might make things work better if you go through an actual server.

If you've got Python installed (it's included on Linux and Mac), the easiest way to do that is to open up the terminal and browse to your code's directory. Then launch a simple Python server:

cd /home/your_user_name/your_directory
python -m SimpleHTTPServer

That will start up a web server which you can access in your browser by navigating to http://localhost:8000/your_file.html.

If you are on Windows and haven't got Python installed, you could also use the built-in IIS server, or WAMP (or just install Python).

Community
  • 1
  • 1
cjol
  • 1,311
  • 7
  • 22
0
y.innerHTML = 'Hello World';

will replace everything in the 'x' element with the text 'Hello World', but it looks like you've already loaded another HTML document into the 'x' element. So the question is...

Where exactly in the 'x' element do you want to insert the text? for example 'x' -> html -> body?

markmanx
  • 11
  • 1
  • browser load text file automatically and insert text in object, simply i don't know how retrive information –  Aug 20 '15 at 13:23
0

The object element is loading the text file asynchronously, so if you try to get its data by querying the element, you'll get undefined.

However, you can use the onload attribute in <object> elements.

In your HTML, add an onload that calls a function in your script to catch when the text file has fully loaded.

<object id="x" onload="getData()" data="readme.txt"></object>

In the script, you can get the object's data with contentDocument.

function getData() {
    var textFile = document.getElementById('x').contentDocument;
    /* The <object> element renders a whole 
       HTML structure in which the data is loaded.
       The plain text representation in the DOM is surrounded by <pre> 
       so we need to target <pre> in the <object>'s DOM tree */

    // getElementByTagsName returns an array of matches.
    var textObject = textFile.getElementsByTagName('pre')[0];
    // I'm sure there are far better ways to select the containing element!.

    /*We retrieve the inner HTML from the object*/
    var text = textObject.innerHTML;

    alert(text); //use the content!
}
Jesús Otero
  • 187
  • 3
  • 16