The FileDialog app contains just one file FileDialog.html, which relies on the shipped FileBrowser app to provide the dialog window. (We can switch later to another undelying app, but the communication with FileDialog.html will remain the same.)
FileDialog.html is designed to be embedded inside iframes.
Create an iframe with the URL pointing to FileDialog.html with a query string containing the following 3 arguments:
type | dialog type: "open", "save", "dir" (the latter is for choosing a directory, not a file) |
filter | a string containing descriptions of file filters to look for; each description is some text followed by file masks in parentheses; filters are delimited by \n (%0A), extensions are delimited by ","; all blanks, pluses, and other non-URI characters must be escaped (e.g., "C++ file" => "C%2B%2B%20file") Example: "Word%20document%20(*.doc,*.rtf)%0AC%2B%2B%20file(*.cpp,*.h,*.hpp)", which decodes to "Word document (*.doc,*.rtf)\nC++ file(*.cpp,*.h,*.hpp)". |
browse_id | some id representing the file browse dialog; can be used to distinguish multiple dialogs when the return value is recevied via a HTML5 message; a good suggestion is to use the current timestamp |
start_dir | the directory to start with (relative to the user's home) |
URL example for the FileDialog.html iframe:
/apps/filedialog/FileDialog.html?type=open&filter=Word%20document%20(*.doc,*.rtf)%0AC%2B%2B%20file(*.cpp,*.h,*.hpp)&browse_id=12345
An example of the full iframe tag:
<iframe id='theiframe' style='width:700px;height:465px;' src='/apps/filedialog/FileDialog.html?type=open&filter=Word%20document%20(*.doc,*.rtf)&browse_id=12345'>
</iframe>
When the file has been selected, FileDialog.html sends back a HTML5 message to its parent frame (the caller):
window.parent.postMessage({protocol:"file_dialog_result", browse_id:"{passed_browse_id}", result: <chosen_file_name_relative_to_user's_home>}, "*");
If the Cancel button is pressed, the message will be:
window.parent.postMessage({protocol:"file_dialog_result", browse_id:"{passed_browse_id}", result: ""}, "*");
An example of the function for receiving the dialog result:
<script>
var receiveMessage2 = function(event) {
if (event.data.browse_id!="12345") return;
alert(event.data.result); // here is your file name
};
window.addEventListener("message", receiveMessage2, true);
</script>
The FileDailog app does not destroy its iframe, neither does it react to outer "x" buttons that can be provided by the outer window or div.
It is your responsibility to destroy the iframe containing the dialog. For example, you can just remove the iframe element from the DOM. If you use some outer window for the iframe, you should destroy it as well.
If you have the "x" button in the outer window, you must implement the corresponding event handler (in this case, assume the dialog result is ""; notice that this result won't be sent by the FileDialog app, since it knows nothing about the outer window).