Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access plain text content retrieved via <script type="text/plain" src=...> in JavaScript?

Tags:

When using <script type="text/plain" src="http://..."></script>, where the URL refers to a plain text file, is there a way to access the content of the file in JavaScript? The file is transferred to the browser, but the value of innerHTML property of the script element is not changed (it remains the empty string). Inspecting the element node in the DOM does not seem to reveal any property through which the content received could be found.

I know that XMLHTTPRequest can be used instead, but I’m interested in the problem why browsers fetch data in the way I described but do not seem to offer any access to it.

like image 646
Jukka K. Korpela Avatar asked Oct 06 '12 14:10

Jukka K. Korpela


1 Answers

First of all, the textattribute of the HTMLScriptElement is the preferred method to access the text of an inline <script> element. DOM-Level-2 and HTML5: 4.11.1 both indicate that a script should have an attribute text which contains the scripts interior text:

The IDL attribute text must return a concatenation of the contents of all the Text nodes that are children of the script element (ignoring any other nodes such as comments or elements), in tree order. On setting, it must act the same way as the textContent IDL attribute.

Since the <script> element is empty (you specified an external source), text, textContent and innerHTML are empty. This is because the text attribute is only set in inline scripts:

If the script is inline and the script block's type is a text-based language:

The value of the text IDL attribute at the time the element's "already started" flag was last set is the script source.

So it's not possible to include an external text/plain using this method.

See also:

  • W3C: HTML5: 4.11.1 The script element: text attribute and the example for the game map:
    <script src="game-engine.js"></script> <!-- game engine isn't inline -->
    <script type="text/x-game-map"> <!-- but data needs to be inline -->
    ........U.........e
    o............A....e
    .....A.....AAA....e
    .A..AAA...AAAAA...e
    </script>
    
like image 52
Zeta Avatar answered Sep 23 '22 05:09

Zeta