Jorge C. S. Cardoso, DEI, Faculdade de Ciências e Tecnologia, Universidade de Coimbra Rua Sílvio Lima, Univ.
Coimbra - Pólo II, 3030-790 Coimbra Portugal
Listing a user directory with javascript in a Chrome extension
javascript
30 Aug 2012
I have been struggling with a way to get my Google Chrome extension to be able to list a user’s directory in order to automatically load and display files from that directory. It turns out, there is no easy way to list the files in an arbitrary directory in a user’s filesystem using Javascript, even in a Chrome extension. The File API in HTML 5 allows web apps to have their own filesystem, but it is an isolated filesystem so that’s no good. You can actually read the contens of a file using XMLRequest (for example this code from Read local file with XmlHttpRequest - JavaScript - Snipplr Social Snippet Repository does just that):
However, it does not allow you to list the directory itself, which is what I was looking for.
My solution is a bit complicated, and not elegant at all, but it works. The only catch is that it requires the Chrome extension to have access to file URLs, which is something that users must explicitly activat in the extensions page.
The solution is:
Open a new Tab
Load that tab with a file URL: file://[user directory to list]. That creates a page that looks like
Inject a piece of javascript into the tab, that
Parses the DOM of the tab’s document, looking for the files listed