简体   繁体   中英

Allow user to import a file from a Greasemonkey script?

From what I can gather this does not even seem possible but here goes:

I am finishing up a Greasemonkey script. In this script the end user is able to save certain things to an html5 localStorage variable (not the purpose of the script, only for one part of it).

Since a cache clear can wipe these storage values I have created an export feature which is simply an unknown datatype which forces a download of the file.

data:something;charset=utf-8,'+encodeURIComponent(somevariable)

My question is on creating an import feature. Since the file saves with no extension and this script will be used exclusively in Linux, opening the file directly in a text program and pasting the data into a textarea would be an easy way to import.

However, is there any way without some sort of server-side scripting or external server to let the user choose a file to import? Such as a dialog box that allows the end-user to select the file from the computer in which I can then manipulate from my end?

HTML5 introduces the HTML5 File API

Using the File API, which was added to the DOM in HTML5, it's now possible for web content to ask the user to select local files, then read the contents of those files. This selection can be done by either using an HTML element, or by drag and drop.

You can hook on change events and check evt.target.files;

Also, you can use Blobs to handle your data, you don't have to rely on data uris.

Here is a good tutorial about it

HTML 5 File API to the rescue!

http://www.html5rocks.com/en/tutorials/file/dndfiles/

Not supported in IE9, but most modern browser do support it : http://caniuse.com/#search=file%20api

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM