How to read the contents of a file inside an epub using javascript ?

5 posts / 0 new
Last post


I need to read, inside a page of an epub3 book, the contents of one of the file of that same epub, being some data to process with a javascript function. Unfortunately, Javascript prevents from loading local files for security reasons. (e.g the File API only allows loading uploaded user files).

But for me in the context of an epub3, it makes sense and I didn't find any information in the IDPF EPUB3 documentation related to this topic.

Any idea ?

OK. Let's clarify:

I have an epub3 with the following structure:


In page.xhtml, I want to write in Javascript something like:

<script type="text/javascript">
//pseudo code
var indata = readAsText("../data/data.xml"); // how to write that ???
var outdata = myfunction(indata);

Thank you.

You need to do an xmlhttprequest to get the file.

Unfortunately, isn't showing data for support of local requests using xmlhttprequest due a recent change, but I think in most cases if the function is defined that it is possible (remote requests are the less likely to succeed).

Alternatively, you could embed the data inside a script tag and then grab the contents and read it into a dom tree using DOMParser.

EPUB requires anyway an accessible alternative for the file and the script approach, why to worry about such a script issue, should be enough to realise the accessible alternative without scripting as a static file, XHTML or SVG.


As you say it's hard finding xmlhttprequest examples for local request and I cannot debug under Readium any longer (or didn't find how to do).
Would the could look like :

var request=new XMLHttpRequest();'GET','../data/data.xml',false);
if(200!==request.status) ; // .... failed
else outdata=myfunction(request.responseText);

Otherwise, I agree that in any case this way of proceeding is not really convenient. Reading files of the proper epub should be more straightforward, not relying on means for accessing remote files .. locally.

If you want to see the test suite code, it's here:

It might seem like a pain, but it's the web way of getting the content. Local file system access via script would come with major security issues, and as someone recently said, what you do own your own site is your business, but reading systems are effectively hosting foreign content on someone else's system (or under the vendor's own domain, if web-based), so they have a lot of pressure to be restrictive.

Secondary menu