Is there anything like webBrowser in javaScript in chrome? [duplicate] - javascript
I know that client-side Javascript cannot write data to the local filesystem, for obvious security reasons.
The only way to save data locally with Javascript seems to be with cookies, localStorage, or allow the user to download a file (with a "Save..." dialog box or to the browser's default Download folder).
But is it possible, in the very specific case when the file is accessed locally with an URL like file:///D:/test/index.html (and not through internet) to write data locally ? (without any server language, and even without any server at all: just local browsing of a HTML file)
For example, would it be possible, by clicking on SAVE here:
<div contenteditable="true" style="height:200px;">Content editable - edit me and save!</div>
<button>Save</button>
...that such a HTML file (accessed through file:///D:/test/index.html) is overwritten with its new content ? (i.e. the local HTML file should be updated when SAVE is pressed).
TL;DR: Is this possible to SAVE a file thanks to Javascript, when the HTML page is accessed locally?
Note: I want to be able to silently save, not propose a Download/Save dialog box in which the user has to choose where to download, then "Are you sure to want to overwrite" etc.
EDIT : Why this question? I'm doing an in-browser notepad that I can run locally without any server (no Apache, no PHP). I need to be able to save easily without having to deal with Dialog Box "Where do you want to download the file?" and having to always re-browse to the same folder to overwrite the currently-being-edited file. I would like a simple UX like in any notepad program: CTRL+S done, the current file is saved! (example: MS Word doesn't ask to browse where you want to save the file each time you do "Save": CTRL+S, done!)
You can just use the Blob function:
function save() {
var htmlContent = ["your-content-here"];
var bl = new Blob(htmlContent, {type: "text/html"});
var a = document.createElement("a");
a.href = URL.createObjectURL(bl);
a.download = "your-download-name-here.html";
a.hidden = true;
document.body.appendChild(a);
a.innerHTML = "something random - nobody will see this, it doesn't matter what you put here";
a.click();
}
and your file will save.
The canonical answer, from the W3C File API Standard:
User agents should provide an API exposed to script that exposes the features above. The user is notified by UI anytime interaction with the file system takes place, giving the user full ability to cancel or abort the transaction. The user is notified of any file selections, and can cancel these. No invocations to these APIs occur silently without user intervention.
Basically, because of security settings, any time you download a file, the browser will make sure the user actually wants to save the file. Browsers don't really differentiate JavaScript on your computer and JavaScript from a web server. The only difference is how the browser accesses the file, so storing the page locally will not make a difference.
Workarounds:
However, you could just store the innerHTML of the <div> in a cookie. When the user gets back, you can load it back from the cookie. Although it isn't exactly saving the file to the user's computer, it should have the same effect as overwriting the file. When the user gets back, they will see what they entered the last time. The disadvantage is that, if the user clears their website data, their information will be lost. Since ignoring a user's request to clear local storage is also a security problem, there really is no way around it.
However, you could also do the following:
Use a Java applet
Use some other kind of applet
Create a desktop (non-Web based) application
Just remember to save the file when you clear your website data. You can create an alert that pops up and reminds you, or even opens the save window for you, when you exit the page.
Using cookies: You can use JavaScript cookies on a local page. Just put this in a file and open it in your browser:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p id="timesVisited"></p>
<script type="text/javascript">
var timesVisited = parseInt(document.cookie.split("=")[1]);
if (isNaN(timesVisited)) timesVisited = 0;
timesVisited++;
document.cookie = "timesVisited=" + timesVisited;
document.getElementById("timesVisited").innerHTML = "You ran this snippet " + timesVisited + " times.";
</script>
</body>
</html>
Chromium's File System Access API (introduced in 2019)
There's a relatively new, non-standard File System Access API (not to be confused with the earlier File and Directory Entries API or the File System API). It looks like it was introduced in 2019/2020 in Chromium/Chrome, and doesn't have support in Firefox or Safari.
When using this API, a locally opened page can open/save other local files and use the files' data in the page. It does require initial permission to save, but while the user is on the page, subsequent saves of specific files do so 'silently'. A user can also grant permission to a specific directory, in which subsequent reads and writes to that directory don't require approval. Approval is needed again after the user closes all the tabs to the web page and reopens the page.
You can read more about this newish API at https://web.dev/file-system-access/. It's meant to be used to make more powerful web applications.
A few things to note about it:
By default, it requires a secure context to run. Running it on https, localhost, or through file:// should work.
You can get a file handle from dragging and dropping a file by using DataTransferItem.getAsFileSystemHandle
Initially reading or saving a file requires user approval and can only be initiated via a user interaction. After that, subsequent reads and saves don't need approval, until the site is opened again.
Handles to files can be saved in the page (so if you were editing 'path/to/file.html', and reload the page, it would be able to have a reference to the file). They can't seemingly be stringified, so are stored through something like IndexedDB (see this answer for more info). Using stored handles to read/write requires user interaction and user approval.
Here are some simple examples. They don't seem to run in a cross-domain iframe, so you probably need to save them as an html file and open them up in Chrome/Chromium.
Opening and Saving, with Drag and Drop (no external libraries):
<body>
<div><button id="open">Open</button><button id="save">Save</button></div>
<textarea id="editor" rows=10 cols=40></textarea>
<script>
let openButton = document.getElementById('open');
let saveButton = document.getElementById('save');
let editor = document.getElementById('editor');
let fileHandle;
async function openFile() {
try {
[fileHandle] = await window.showOpenFilePicker();
await restoreFromFile(fileHandle);
} catch (e) {
// might be user canceled
}
}
async function restoreFromFile() {
let file = await fileHandle.getFile();
let text = await file.text();
editor.value = text;
}
async function saveFile() {
var saveValue = editor.value;
if (!fileHandle) {
try {
fileHandle = await window.showSaveFilePicker();
} catch (e) {
// might be user canceled
}
}
if (!fileHandle || !await verifyPermissions(fileHandle)) {
return;
}
let writableStream = await fileHandle.createWritable();
await writableStream.write(saveValue);
await writableStream.close();
}
async function verifyPermissions(handle) {
if (await handle.queryPermission({ mode: 'readwrite' }) === 'granted') {
return true;
}
if (await handle.requestPermission({ mode: 'readwrite' }) === 'granted') {
return true;
}
return false;
}
document.body.addEventListener('dragover', function (e) {
e.preventDefault();
});
document.body.addEventListener('drop', async function (e) {
e.preventDefault();
for (const item of e.dataTransfer.items) {
if (item.kind === 'file') {
let entry = await item.getAsFileSystemHandle();
if (entry.kind === 'file') {
fileHandle = entry;
restoreFromFile();
} else if (entry.kind === 'directory') {
// handle directory
}
}
}
});
openButton.addEventListener('click', openFile);
saveButton.addEventListener('click', saveFile);
</script>
</body>
Storing and Retrieving a File Handle using idb-keyval:
Storing file handles can be tricky, since they can't be unstringified, though apparently they can be used with IndexedDB and mostly with history.state. For this example we'll use idb-keyval to access IndexedDB to store a file handle. To see it work, open or save a file, and then reload the page and press the 'Restore' button. This example uses some code from https://stackoverflow.com/a/65938910/.
<body>
<script src="https://unpkg.com/idb-keyval#6.1.0/dist/umd.js"></script>
<div><button id="restore" style="display:none">Restore</button><button id="open">Open</button><button id="save">Save</button></div>
<textarea id="editor" rows=10 cols=40></textarea>
<script>
let restoreButton = document.getElementById('restore');
let openButton = document.getElementById('open');
let saveButton = document.getElementById('save');
let editor = document.getElementById('editor');
let fileHandle;
async function openFile() {
try {
[fileHandle] = await window.showOpenFilePicker();
await restoreFromFile(fileHandle);
} catch (e) {
// might be user canceled
}
}
async function restoreFromFile() {
let file = await fileHandle.getFile();
let text = await file.text();
await idbKeyval.set('file', fileHandle);
editor.value = text;
restoreButton.style.display = 'none';
}
async function saveFile() {
var saveValue = editor.value;
if (!fileHandle) {
try {
fileHandle = await window.showSaveFilePicker();
await idbKeyval.set('file', fileHandle);
} catch (e) {
// might be user canceled
}
}
if (!fileHandle || !await verifyPermissions(fileHandle)) {
return;
}
let writableStream = await fileHandle.createWritable();
await writableStream.write(saveValue);
await writableStream.close();
restoreButton.style.display = 'none';
}
async function verifyPermissions(handle) {
if (await handle.queryPermission({ mode: 'readwrite' }) === 'granted') {
return true;
}
if (await handle.requestPermission({ mode: 'readwrite' }) === 'granted') {
return true;
}
return false;
}
async function init() {
var previousFileHandle = await idbKeyval.get('file');
if (previousFileHandle) {
restoreButton.style.display = 'inline-block';
restoreButton.addEventListener('click', async function (e) {
if (await verifyPermissions(previousFileHandle)) {
fileHandle = previousFileHandle;
await restoreFromFile();
}
});
}
document.body.addEventListener('dragover', function (e) {
e.preventDefault();
});
document.body.addEventListener('drop', async function (e) {
e.preventDefault();
for (const item of e.dataTransfer.items) {
console.log(item);
if (item.kind === 'file') {
let entry = await item.getAsFileSystemHandle();
if (entry.kind === 'file') {
fileHandle = entry;
restoreFromFile();
} else if (entry.kind === 'directory') {
// handle directory
}
}
}
});
openButton.addEventListener('click', openFile);
saveButton.addEventListener('click', saveFile);
}
init();
</script>
</body>
Additional Notes
Firefox and Safari support seems to be unlikely, at least in the near term. See https://github.com/mozilla/standards-positions/issues/154 and https://lists.webkit.org/pipermail/webkit-dev/2020-August/031362.html
Yes, it's possible.
In your example, you are already using ContentEditable and most of tutorials for that attribute have some sort of localStrorage example, ie. http://www.html5tuts.co.uk/demos/localstorage/
On page load, script should check localStorage for data and if true, populate element. Any changes in content could be saved in localStorage when clicking save button (or automatically, in linked example, using blur and focus). Additionally you can use this snippet to check weather user is online or offline and based on state modify your logic:
// check if online/offline
// http://www.kirupa.com/html5/check_if_internet_connection_exists_in_javascript.htm
function doesConnectionExist() {
var xhr = new XMLHttpRequest();
var file = "http://www.yoursite.com/somefile.png";
var randomNum = Math.round(Math.random() * 10000);
xhr.open('HEAD', file + "?rand=" + randomNum, false);
try {
xhr.send();
if (xhr.status >= 200 && xhr.status < 304) {
return true;
} else {
return false;
}
} catch (e) {
return false;
}
}
EDIT: More advance version of localStorage is Mozilla localForage which allows storing other types of data besides strings.
You could save files, and make it persistent using the FileSystem-API and webkit. You would have to use a chrome browser and it is not a standards technology but I think it does exactly what you want it to do. Here is a great tutorial to show how to do just that http://www.noupe.com/design/html5-filesystem-api-create-files-store-locally-using-javascript-webkit.html
And to show that its on topic it starts off showing you how to make the file save persistent...
window.webkitRequestFileSystem(window.PERSISTENT , 1024*1024, SaveDatFileBro);
Convert your HTML content to a data uri string, and set as href attribute of an anchor element. Don't forget to specify a filename as download attribute.
Here's a simple example:
<a>click to download</a>
<script>
var anchor = document.querySelector('a');
anchor.setAttribute('download', 'example.html');
anchor.setAttribute('href', 'data:text/html;charset=UTF-8,<p>asdf</p>');
</script>
Just try it in your browser, no server required.
Have a look into this :)
Download File Using Javascript/jQuery
there should be everything you need. If you still need help or it's not the solution you need, tell me ;)
Yes, it is possible. Proof by example:
TiddlyFox: allows modification of local files via an add-on. (source code) (extension page):
TiddlyFox is an extension for Mozilla Firefox that enables TiddlyWiki
to save changes directly to the file system.
Todo.html: An HTML file that saves edits to itself. Currently, it only works in Internet Explorer and you have to confirm some security dialogs when first opening the file. (source code) (functional demo).
Steps to confirm todo.html actually saves changes to itself locally:
Save todo.html to local harddrive
Open with Internet Explorer. Accept all the security dialogs.
Type command todo add TEST (todo.html emulates the command-line interface of todo.txt-CLI)
Inspect todo.html file for addition of 'TEST'
Caveats: there is no cross-platform method. I'm not sure how much longer these methods will exist. When I first started my todo.html project, there was a jQuery plugin called twFile that allowed cross-browser loading/saving of local files using four different methods (ActiveX, Mozilla XUL, Java applet, Java Live Connect). Except for ActiveX, browsers have disallowed all these methods due to security concerns.
If you are fine with your code running outside of the scope of your default browser, and you are fine with windows only support, HTAs meet the silently save without prompts requirement easily.
The below code doesn't use many HTA specific features but it does still use microsoft specific stuff like ActiveXObject("Scripting.FileSystemObject").
<html>
<head>
<title>Simple Notepad</title>
<meta http-equiv="X-UA-Compatible" content="IE=9">
<script>
document.addEventListener('keydown', function (event) {
if (event.ctrlKey) {
if (event.key == 's') {
var FSo = new ActiveXObject("Scripting.FileSystemObject");
//see https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/opentextfile-method
var thisFile = FSo.OpenTextFile(window.location.pathname, 2, true, -1);
thisFile.Write(document.getElementsByTagName("html")[0].outerHTML);
thisFile.Close();
// Comment out the below alert to get truly silent saving.
alert('Saved Successfully');
if (event.preventDefault) event.preventDefault();
return false;
}
}
}, false);
</script>
</head>
<body contentEditable="true">
<h1>Press <kbd>CTRL + S</kbd> To Save</h1>
</body>
</html>
It also isn't a very rich editing experience but that can be fixed with some more buttons or keyboard shortcuts I think. Like CTRL + B to embolden selected text. It doesn't have any safety checks as of yet, but binding an event handler to beforeunload should prevent any data loss caused by accidentally closing the program.
HTA's do have other disadvantages too. They don't support ES6 (though transpiling is an option).
Although it is a bit dated, If you're not trying to use modern web features, I think you'll agree that it is very functional and usable.
Edit
I forgot to mention, but HTAs have to be saved with the .hta file extension for mshta.exe to be registered as their file type handler. Which is needed so that you can double click it in windows explorer to open it easily.
See also
Introduction to HTML Applications on MSDN
HTML Applications reference on MSDN
I think it's important to clarify the difference between server and client in this context.
Client/server is a program relationship in which one program (the client) requests a service or resource from another program (the server).
Source: http://searchnetworking.techtarget.com/definition/client-server
I'm not sure you'll find too many advanced applications that don't have at least one server/client relationship. It is somewhat misleading to ask to achieve this without any server, because any time your program speaks to another program, it is a client/server relationship, with the requester being the client and the response coming from the server. This is even if you are working locally. When you want to do something outside of the scope of the browser, you need a hook in a server.
Now, that does not mean you can't achieve this without a server-side specific language. For example, this solution uses NodeJS for the server. WinJS has WinJS.xhr, which uses XmlHttpRequest to serve data to the server.
AJAX seeks to offer the same sort of functions. The point here is that whether you have a program or there is some sort of hook pre-built, when you issue a command like "save file" and the file actually gets saved, there is a program on the other side that is parsing it, whether it's a server-side language or something else, meaning you can't possibly have something like this function without a server to receive the request.
Just use https://github.com/firebase/firepad — See it in action
This doesn’t need a server on your computer, it will reach out and save the data remotely.
Use jsPDF -> https://github.com/MrRio/jsPDF
<div id="content">
<h3>Hello, this is a H3 tag</h3>
<p>a pararaph</p>
</div>
<div id="editor"></div>
<button id="cmd">generate PDF</button>
Javascript
var doc = new jsPDF();
var specialElementHandlers = {
'#editor': function (element, renderer) {
return true;
}
};
$('#cmd').click(function () {
doc.fromHTML($('#content').html(), 15, 15, {
'width': 170,
'elementHandlers': specialElementHandlers
});
doc.save('sample-file.pdf');
});
This is an example for those who want to know how to use the localStorage.
<div id="divInput" contenteditable="true" style="height:200px;border: 2px solid blue">
Content editable - edit me and save!
</div>
<button onclick="onSave()">Save</button>
<button onclick="onLoad()">Load</button>
<script>
config = {
localStorageItemName: "demo",
datetimeFormat: {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
hour12: false,
minute: '2-digit',
second: '2-digit'
}
}
function Now() {
return new Date().toLocaleString("zh-TW", config.datetimeFormat)
}
const errMap = {
IsEmptyError: new Error('is empty'),
LengthError: new Error('length = 0')
}
/**
* #param {string} itemName
* #return {Object}
* */
function getLocalStorageItem(itemName) {
const dbDataString = localStorage.getItem(itemName)
if (dbDataString === null) {
throw errMap.IsEmptyError
}
const db = JSON.parse(dbDataString)
if (Object.keys(db).length === 0) {
throw errMap.LengthError
}
return db
}
function onSave() {
const inputValue = document.querySelector(`#divInput`).textContent
try {
const db = getLocalStorageItem(config.localStorageItemName)
db.msg = inputValue
db.lastModTime = Now()
localStorage.setItem(config.localStorageItemName, JSON.stringify(db))
console.log("save OK!")
} catch (err) {
switch (err) {
case errMap.IsEmptyError:
console.info("new localStorageItemName")
localStorage.setItem(config.localStorageItemName,
JSON.stringify({msg: inputValue, createTime: Now()})
)
break
/*
case ...
break
*/
default:
console.error(err.message)
}
}
}
function onLoad(e) {
try {
const db = getLocalStorageItem(config.localStorageItemName)
console.log("load")
document.querySelector(`#divInput`).textContent = db.msg
} catch (err) {
return
}
}
(()=>{
window.onload = () => (
onLoad()
)
})()
</script>
It is written in pure javascript with no dependencies.
Related
How automatic download works using blob URL's and programmatic click events?
I recently needed to implement an automatic download of a CSV file in javascript. I didn't want to use any 3rd party libraries so instead I studies how the 3rd party libraries do it. I took a look at FileSaver npm package specifically at the function saveAs from here. Eventually I changed the code to suit my needs into something like this: class BlobDownload { constructor(window, blob, fileName, contentType) { this.window = window; this.document = window.document; this.blob = blob; this.fileName = fileName; this.contentType = contentType; } asyncCreateObjectURL = blob => { return new Promise((resolve, reject) => { const blobURL = this.window.URL.createObjectURL(blob); blobURL ? resolve(blobURL) : reject(); }); } click = (node) => { try { node.dispatchEvent(new MouseEvent('click')); } catch (e) { const evt = this.document.createEvent('MouseEvents'); evt.initMouseEvent('click', true, true, this.window, 0, 0, 0, 80, 20, false, false, false, false, 0, null); node.dispatchEvent(evt); } }; download = async () => { const blob = new Blob([this.blob], { type: this.contentType }); const a = this.document.createElement('a'); a.download = this.fileName; a.href = await this.asyncCreateObjectURL(blob); setTimeout(() => { this.window.URL.revokeObjectURL(a.href) }, 60000) // 1min setTimeout(() => { this.click(a) }, 0) } } export default BlobDownload; I don't understand a few things in the code though: we're create an a node but it doesn't display anywhere on the page. Where does this node actually reside, only as an object in RAM? the function click dispatched click event immediately, but if this doesn't work it creates a new event and then dispatches it. Why do we need to account for the case where simple dispatching doesn't work? the whole procedure of creating an temporary a link and artificially clicking on it seems like a hack. Is this really a good pattern or better practices exist to download files?
we're create an a node but it doesn't display anywhere on the page. Where does this node actually reside, only as an object in RAM? Yes, it will only reside in the memory but it's still possible to call an event on it as evident by the source code. Note: this will not work on iOS Safari. There you have to display the actual link and prompt the user to tap it - there's a note about it on FileSaver.js's README.md. the function click dispatched click event immediately, but if this doesn't work it creates a new event and then dispatches it. Why do we need to account for the case where simple dispatching doesn't work? Reading the MDN page for initMouseEvent tells us it deprecated. If the click function fails and the try-catch is triggered then we're on a really old browser where initMouseEvent should be available. If you go back in the commit history the code used to be far more complicated due to edge cases and ultimately not needed feature detection. the whole procedure of creating an temporary a link and artificially clicking on it seems like a hack. Is this really a good pattern or better practices exist to download files? It's a hack, there's no way around it. Best practices won't get you far if you need to have backwards compatibility. FileSaver.js strives to abstract away all of the gnarly hacking needed to handle programmatic file saving so that you don't have to. In general I would advise against copying over library code for a custom implementation. FileSaver.js is over 9 years old now and still relevant. Having it as a package.json dependency or a copy-paste in a library folder would preserve it's attribution making maintenance easier on the next guy :). In general it's a good set of questions! I'm also implementing a CSV download feature right now. I stumbled on it from googling based on this SO answer while trying to get file saving to work with Web Workers without the need to postMessage the contents of a file. Apparently passing only an URL to a blob is enough for saveAs to work! // in web worker return from promise-worker/postMessage -> URL.createObjectURL(new Blob([data], { type: 'text/csv;charset=utf-8;' })); // on main thread saveAs(objectURLCreatedAbove); // done :) Consider using Web Workers if your CSV's get big and there are considerable freezes when you prepare data for downloading. The sheetjs library is also quite helpful if you need to do anything with spreadsheet data. Happy coding!
JS/jQuery listen for page change cancel due to downloaded file [duplicate]
I have a page that allows the user to download a dynamically-generated file. It takes a long time to generate, so I'd like to show a "waiting" indicator. The problem is, I can't figure out how to detect when the browser has received the file so that I can hide the indicator. I'm requesting a hidden form, which POSTs to the server, and targets a hidden iframe for its results. This is, so I don't replace the entire browser window with the result. I listen for a "load" event on the iframe, hoping that it will fire when the download is complete. I return a "Content-Disposition: attachment" header with the file, which causes the browser to show the "Save" dialog. But the browser doesn't fire a "load" event in the iframe. One approach I tried is using a multi-part response. So it would send an empty HTML file, as well as the attached downloadable file. For example: Content-type: multipart/x-mixed-replace;boundary="abcde" --abcde Content-type: text/html --abcde Content-type: application/vnd.fdf Content-Disposition: attachment; filename=foo.fdf file-content --abcde This works in Firefox; it receives the empty HTML file, fires the "load" event, and then shows the "Save" dialog for the downloadable file. But it fails on Internet Explorer and Safari; Internet Explorer fires the "load" event, but it doesn't download the file, and Safari downloads the file (with the wrong name and content-type) and doesn't fire the "load" event. A different approach might be to call to start the file creation, poll the server until it's ready, and then download the already-created file. But I'd rather avoid creating temporary files on the server. What should I do?
One possible solution uses JavaScript on the client. The client algorithm: Generate a random unique token. Submit the download request, and include the token in a GET/POST field. Show the "waiting" indicator. Start a timer, and every second or so, look for a cookie named "fileDownloadToken" (or whatever you decide). If the cookie exists, and its value matches the token, hide the "waiting" indicator. The server algorithm: Look for the GET/POST field in the request. If it has a non-empty value, drop a cookie (e.g. "fileDownloadToken"), and set its value to the token's value. Client source code (JavaScript): function getCookie( name ) { var parts = document.cookie.split(name + "="); if (parts.length == 2) return parts.pop().split(";").shift(); } function expireCookie( cName ) { document.cookie = encodeURIComponent(cName) + "=deleted; expires=" + new Date( 0 ).toUTCString(); } function setCursor( docStyle, buttonStyle ) { document.getElementById( "doc" ).style.cursor = docStyle; document.getElementById( "button-id" ).style.cursor = buttonStyle; } function setFormToken() { var downloadToken = new Date().getTime(); document.getElementById( "downloadToken" ).value = downloadToken; return downloadToken; } var downloadTimer; var attempts = 30; // Prevents double-submits by waiting for a cookie from the server. function blockResubmit() { var downloadToken = setFormToken(); setCursor( "wait", "wait" ); downloadTimer = window.setInterval( function() { var token = getCookie( "downloadToken" ); if( (token == downloadToken) || (attempts == 0) ) { unblockSubmit(); } attempts--; }, 1000 ); } function unblockSubmit() { setCursor( "auto", "pointer" ); window.clearInterval( downloadTimer ); expireCookie( "downloadToken" ); attempts = 30; } Example server code (PHP): $TOKEN = "downloadToken"; // Sets a cookie so that when the download begins the browser can // unblock the submit button (thus helping to prevent multiple clicks). // The false parameter allows the cookie to be exposed to JavaScript. $this->setCookieToken( $TOKEN, $_GET[ $TOKEN ], false ); $result = $this->sendFile(); Where: public function setCookieToken( $cookieName, $cookieValue, $httpOnly = true, $secure = false ) { // See: http://stackoverflow.com/a/1459794/59087 // See: http://shiflett.org/blog/2006/mar/server-name-versus-http-host // See: http://stackoverflow.com/a/3290474/59087 setcookie( $cookieName, $cookieValue, 2147483647, // expires January 1, 2038 "/", // your path $_SERVER["HTTP_HOST"], // your domain $secure, // Use true over HTTPS $httpOnly // Set true for $AUTH_COOKIE_NAME ); }
A very simple (and lame) one line solution is to use the window.onblur() event to close the loading dialog. Of course, if it takes too long and the user decides to do something else (like reading emails) the loading dialog will close.
This solution is very simple, yet reliable. And it makes it possible to display real progress messages (and can be easily plugged in to existing processes): The script that processes (my problem was: retrieving files via HTTP and deliver them as ZIP) writes the status to the session. The status is polled and displayed every second. that’s all (OK, it’s not. You have to take care of a lot of details (for example, concurrent downloads), but it’s a good place to start ;-)). The download page: DOWNLOAD 1 DOWNLOAD 2 ... <div id="wait"> Please wait... <div id="statusmessage"></div> </div> <script> // This is jQuery $('a.download').each(function() { $(this).click( function() { $('#statusmessage').html('prepare loading...'); $('#wait').show(); setTimeout('getstatus()', 1000); } ); }); }); function getstatus() { $.ajax({ url: "/getstatus.php", type: "POST", dataType: 'json', success: function(data) { $('#statusmessage').html(data.message); if(data.status == "pending") setTimeout('getstatus()', 1000); else $('#wait').hide(); } }); } </script> File getstatus.php <?php session_start(); echo json_encode($_SESSION['downloadstatus']); ?> File download.php <?php session_start(); $processing = true; while($processing) { $_SESSION['downloadstatus'] = array("status" =>"pending", "message" => "Processing".$someinfo); session_write_close(); $processing = do_what_has_2Bdone(); session_start(); } $_SESSION['downloadstatus'] = array("status" => "finished", "message" => "Done"); // And spit the generated file to the browser ?>
The core problem is that the web browser does not have an event that fires when page navigation is cancelled but does have an event that fires when a page completes loading. Anything outside of a direct browser event is going to be a hack with pros and cons. There are four known approaches to dealing with detecting when a browser download starts: Call fetch(), retrieve the entire response, attach an a tag with a download attribute, and trigger a click event. Modern web browsers will then offer the user the option to save the already retrieved file. There are several downsides with this approach: The entire data blob is stored in RAM, so if the file is large, it will consume that much RAM. For small files, this probably isn't a deal breaker. The user has to wait for the entire file to download before they can save it. They also can't leave the page until it completes. The built-in web browser file downloader is not used. A cross-domain fetch will probably fail unless CORS headers are set. Use an iframe + a server-side cookie. The iframe fires a load event if a page loads in the iframe instead of starting a download but it does not fire any events if the download starts. Setting a cookie with the web server can then be detected by JavaScript in a loop. There are several downsides with this approach: The server and client have to work in concert. The server has to set a cookie. The client has to detect the cookie. Cross-domain requests won't be able to set the cookie. There are limits to how many cookies can be set per domain. Can't send custom HTTP headers. Use an iframe with URL redirection. The iframe starts a request and once the server has prepared the file, it dumps a HTML document that performs a meta refresh to a new URL, which triggers the download 1 second later. The load event on the iframe happens when the HTML document loads. There are several downsides with this approach: The server has to maintain storage for the content being downloaded. Requires a cron job or similar to regularly clean up the directory. The server has to dump out special HTML content when the file is ready. The client has to guess as to when the iframe has actually made the second request to the server and when the download has actually started before removing the iframe from the DOM. This could be overcome by just leaving the iframe in the DOM. Can't send custom HTTP headers. Use an iframe + XHR. The iframe triggers the download request. As soon as the request is made via the iframe, an identical request via XHR is made. If the load event on the iframe fires, an error has occurred, abort the XHR request, and remove the iframe. If a XHR progress event fires, then downloading has probably started in the iframe, abort the XHR request, wait a few seconds, and then remove the iframe. This allows for larger files to be downloaded without relying on a server-side cookie. There are several downsides with this approach: There are two separate requests made for the same information. The server can distinguish the XHR from the iframe by checking the incoming headers. A cross-domain XHR request will probably fail unless CORS headers are set. However, the browser won't know if CORS is allowed or not until the server sends back the HTTP headers. If the server waits to send headers until the file data is ready, the XHR can roughly detect when the iframe has started to download even without CORS. The client has to guess as to when the download has actually started to remove the iframe from the DOM. This could be overcome by just leaving the iframe in the DOM. Can't send custom headers on the iframe. Without an appropriate built-in web browser event, there aren't any perfect solutions here. However, one of the four methods above will likely be a better fit than the others depending on your use-case. Whenever possible, stream responses to the client on the fly instead of generating everything first on the server and then sending the response. Various file formats can be streamed such as CSV, JSON, XML, ZIP, etc. It really depends on finding a library that supports streaming content. When streaming the response as soon as the request starts, detecting the start of the download won't matter as much because it will start almost right away. Another option is to just output the download headers up front instead of waiting for all of the content to be generated first. Then generate the content and finally start sending to the client. The user's built-in downloader will patiently wait until the data starts arriving. The downside is that the underlying network connection could timeout waiting for data to start flowing (either on the client or server side).
Based on Elmer's example, I've prepared my own solution. After clicking on an item with a defined "download" class, a custom message is displayed in the browser window. I used the focus trigger to hide the message. I've used the focus trigger to hide the message. JavaScript $(function(){$('.download').click(function() { ShowDownloadMessage(); }); }) function ShowDownloadMessage() { $('#message-text').text('Your report is creating. Please wait...'); $('#message').show(); window.addEventListener('focus', HideDownloadMessage, false); } function HideDownloadMessage(){ window.removeEventListener('focus', HideDownloadMessage, false); $('#message').hide(); } HTML <div id="message" style="display: none"> <div id="message-screen-mask" class="ui-widget-overlay ui-front"></div> <div id="message-text" class="ui-dialog ui-widget ui-widget-content ui-corner-all ui-front ui-draggable ui-resizable waitmessage">please wait...</div> </div> Now you should implement any element to download: <a class="download" href="file://www.ocelot.com.pl/prepare-report">Download report</a> or <input class="download" type="submit" value="Download" name="actionType"> After each download click you will see the message: Your report is creating. Please wait...
I use the following to download blobs and revoke the object URL after the download. It works in Chrome and Firefox! function download(blob){ var url = URL.createObjectURL(blob); console.log('create ' + url); window.addEventListener('focus', window_focus, false); function window_focus(){ window.removeEventListener('focus', window_focus, false); URL.revokeObjectURL(url); console.log('revoke ' + url); } location.href = url; } After the file download dialog is closed, the window gets its focus back, so the focus event is triggered.
I faced the same problem with that configuration: Struts 1.2.9 jQuery 1.3.2. jQuery UI 1.7.1.custom Internet Explorer 11 Java 5 My solution with a cookie: Client side: When submitting your form, call your JavaScript function to hide your page and load your waiting spinner function loadWaitingSpinner() { ... hide your page and show your spinner ... } Then, call a function that will check every 500 ms whether a cookie is coming from server. function checkCookie() { var verif = setInterval(isWaitingCookie, 500, verif); } If the cookie is found, stop checking every 500 ms, expire the cookie and call your function to come back to your page and remove the waiting spinner (removeWaitingSpinner()). It is important to expire the cookie if you want to be able to download another file again! function isWaitingCookie(verif) { var loadState = getCookie("waitingCookie"); if (loadState == "done") { clearInterval(verif); document.cookie = "attenteCookie=done; expires=Tue, 31 Dec 1985 21:00:00 UTC;"; removeWaitingSpinner(); } } function getCookie(cookieName) { var name = cookieName + "="; var cookies = document.cookie var cs = cookies.split(';'); for (var i = 0; i < cs.length; i++) { var c = cs[i]; while(c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return ""; } function removeWaitingSpinner() { ... come back to your page and remove your spinner ... } Server side: At the end of your server process, add a cookie to the response. That cookie will be sent to the client when your file will be ready for download. Cookie waitCookie = new Cookie("waitingCookie", "done"); response.addCookie(waitCookie);
If you're streaming a file that you're generating dynamically, and also have a realtime server-to-client messaging library implemented, you can alert your client pretty easily. The server-to-client messaging library I like and recommend is Socket.io (via Node.js). After your server script is done generating the file that is being streamed for download your last line in that script can emit a message to Socket.io which sends a notification to the client. On the client, Socket.io listens for incoming messages emitted from the server and allows you to act on them. The benefit of using this method over others is that you are able to detect a "true" finish event after the streaming is done. For example, you could show your busy indicator after a download link is clicked, stream your file, emit a message to Socket.io from the server in the last line of your streaming script, listen on the client for a notification, receive the notification and update your UI by hiding the busy indicator. I realize most people reading answers to this question might not have this type of a setup, but I've used this exact solution to great effect in my own projects and it works wonderfully. Socket.io is incredibly easy to install and use. See more: http://socket.io/
I wrote a simple JavaScript class that implements a technique similar to the one described in bulltorious' answer. I hope it can be useful to someone here. The GitHub project is called response-monitor.js. By default it uses spin.js as the waiting indicator, but it also provides a set of callbacks for implementation of a custom indicator. jQuery is supported, but not required. Notable features Simple integration No dependencies jQuery plug-in (optional) Spin.js Integration (optional) Configurable callbacks for monitoring events Handles multiple simultaneous requests Server-side error detection Timeout detection Cross browser Example usage HTML <!-- The response monitor implementation --> <script src="response-monitor.js"></script> <!-- Optional jQuery plug-in --> <script src="response-monitor.jquery.js"></script> <a class="my_anchors" href="/report?criteria1=a&criteria2=b#30">Link 1 (Timeout: 30s)</a> <a class="my_anchors" href="/report?criteria1=b&criteria2=d#10">Link 2 (Timeout: 10s)</a> <form id="my_form" method="POST"> <input type="text" name="criteria1"> <input type="text" name="criteria2"> <input type="submit" value="Download Report"> </form> Client (plain JavaScript) // Registering multiple anchors at once var my_anchors = document.getElementsByClassName('my_anchors'); ResponseMonitor.register(my_anchors); // Clicking on the links initiates monitoring // Registering a single form var my_form = document.getElementById('my_form'); ResponseMonitor.register(my_form); // The submit event will be intercepted and monitored Client (jQuery) $('.my_anchors').ResponseMonitor(); $('#my_form').ResponseMonitor({timeout: 20}); Client with callbacks (jQuery) // When options are defined, the default spin.js integration is bypassed var options = { onRequest: function(token) { $('#cookie').html(token); $('#outcome').html(''); $('#duration').html(''); }, onMonitor: function(countdown) { $('#duration').html(countdown); }, onResponse: function(status) { $('#outcome').html(status==1 ? 'success' : 'failure'); }, onTimeout: function() { $('#outcome').html('timeout'); } }; // Monitor all anchors in the document $('a').ResponseMonitor(options); Server (PHP) $cookiePrefix = 'response-monitor'; // Must match the one set on the client options $tokenValue = $_GET[$cookiePrefix]; $cookieName = $cookiePrefix.'_'.$tokenValue; // Example: response-monitor_1419642741528 // This value is passed to the client through the ResponseMonitor.onResponse callback $cookieValue = 1; // For example, "1" can interpret as success and "0" as failure setcookie( $cookieName, $cookieValue, time() + 300, // Expire in 5 minutes "/", $_SERVER["HTTP_HOST"], true, false ); header('Content-Type: text/plain'); header("Content-Disposition: attachment; filename=\"Response.txt\""); sleep(5); // Simulate whatever delays the response print_r($_REQUEST); // Dump the request in the text file For more examples, check the examples folder in the repository.
A solution from elsewhere that worked: /** * download file, show modal * * #param uri link * #param name file name */ function downloadURI(uri, name) { // <------------------------------------------ Do something (show loading) fetch(uri) .then(resp => resp.blob()) .then(blob => { const url = window.URL.createObjectURL(blob); const a = document.createElement('a'); a.style.display = 'none'; a.href = url; // the filename you want a.download = name; document.body.appendChild(a); a.click(); window.URL.revokeObjectURL(url); // <---------------------------------------- Detect here (hide loading) alert('File detected'); }) .catch(() => alert('An error sorry')); } You can use it: downloadURI("www.linkToFile.com", "file.name");
I had a real struggle with this exact problem, but I found a viable solution using iframes (I know, I know. It's terrible, but it works for a simple problem that I had.) I had an HTML page that launched a separate PHP script that generated the file and then downloaded it. On the HTML page, I used the following jQuery code in the html header (you'll need to include a jQuery library as well): <script> $(function(){ var iframe = $("<iframe>", {name: 'iframe', id: 'iframe',}).appendTo("body").hide(); $('#click').on('click', function(){ $('#iframe').attr('src', 'your_download_script.php'); }); $('iframe').load(function(){ $('#iframe').attr('src', 'your_download_script.php?download=yes'); <!-- On first iframe load, run script again but download file instead --> $('#iframe').unbind(); <!-- Unbinds the iframe. Helps prevent against infinite recursion if the script returns valid html (such as echoing out exceptions) --> }); }); </script> In file your_download_script.php, have the following: function downloadFile($file_path) { if (file_exists($file_path)) { header('Content-Description: File Transfer'); header('Content-Type: text/csv'); header('Content-Disposition: attachment; filename=' . basename($file_path)); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: ' . filesize($file_path)); ob_clean(); flush(); readfile($file_path); exit(); } } $_SESSION['your_file'] = path_to_file; // This is just how I chose to store the filepath if (isset($_REQUEST['download']) && $_REQUEST['download'] == 'yes') { downloadFile($_SESSION['your_file']); } else { // Execute logic to create the file } To break this down, jQuery first launches your PHP script in an iframe. The iframe is loaded once the file is generated. Then jQuery launches the script again with a request variable telling the script to download the file. The reason that you can't do the download and file generation all in one go is due to the php header() function. If you use header(), you're changing the script to something other than a web page and jQuery will never recognize the download script as being 'loaded'. I know this may not necessarily be detecting when a browser receives a file, but your issue sounded similar to mine.
When the user triggers the generation of the file, you could simply assign a unique ID to that "download", and send the user to a page which refreshes (or checks with AJAX) every few seconds. Once the file is finished, save it under that same unique ID and... If the file is ready, do the download. If the file is not ready, show the progress. Then you can skip the whole iframe/waiting/browserwindow mess, yet have a really elegant solution.
If you don't want to generate and store the file on the server, are you willing to store the status, e.g. file-in-progress, file-complete? Your "waiting" page could poll the server to know when the file generation is complete. You wouldn't know for sure that the browser started the download but you'd have some confidence.
In my experience, there are two ways to handle this: Set a short-lived cookie on the download, and have JavaScript continually check for its existence. Only real issue is getting the cookie lifetime right - too short and the JavaScript can miss it, too long and it might cancel the download screens for other downloads. Using JavaScript to remove the cookie upon discovery usually fixes this. Download the file using fetch/XHR. Not only do you know exactly when the file download finishes, if you use XHR you can use progress events to show a progress bar! Save the resulting blob with msSaveBlob in Internet Explorer or Edge and a download link (like this one) in Firefox and Chrome. The problem with this method is that iOS Safari doesn't seem to handle downloading blobs right - you can convert the blob into a data URL with a FileReader and open that in a new window, but that's opening the file, not saving it.
I just had this exact same problem. My solution was to use temporary files since I was generating a bunch of temporary files already. The form is submitted with: var microBox = { show : function(content) { $(document.body).append('<div id="microBox_overlay"></div><div id="microBox_window"><div id="microBox_frame"><div id="microBox">' + content + '</div></div></div>'); return $('#microBox_overlay'); }, close : function() { $('#microBox_overlay').remove(); $('#microBox_window').remove(); } }; $.fn.bgForm = function(content, callback) { // Create an iframe as target of form submit var id = 'bgForm' + (new Date().getTime()); var $iframe = $('<iframe id="' + id + '" name="' + id + '" style="display: none;" src="about:blank"></iframe>') .appendTo(document.body); var $form = this; // Submittal to an iframe target prevents page refresh $form.attr('target', id); // The first load event is called when about:blank is loaded $iframe.one('load', function() { // Attach listener to load events that occur after successful form submittal $iframe.load(function() { microBox.close(); if (typeof(callback) == 'function') { var iframe = $iframe[0]; var doc = iframe.contentWindow.document; var data = doc.body.innerHTML; callback(data); } }); }); this.submit(function() { microBox.show(content); }); return this; }; $('#myForm').bgForm('Please wait...'); At the end of the script that generates the file I have: header('Refresh: 0;url=fetch.php?token=' . $token); echo '<html></html>'; This will cause the load event on the iframe to be fired. Then the wait message is closed and the file download will then start. It was tested on Internet Explorer 7 and Firefox.
You can rely on the browser's cache and trigger a second download of the same file when the file is loaded to the cache. $('#link').click(function(e) { e.preventDefault(); var url = $(this).attr('href'); var request = new XMLHttpRequest(); request.responseType = "blob"; request.open("GET", url); var self = this; request.onreadystatechange = function () { if (request.readyState === 4) { var file = $(self).data('file'); var anchor = document.createElement('a'); anchor.download = file; console.log(file); console.log(request); anchor.href = window.URL.createObjectURL(request.response); anchor.click(); console.log('Completed. Download window popped up.'); } }; request.send(); });
If you have downloaded a file, which is saved, as opposed to being in the document, there isn't any way to determine when the download is complete, since it is not in the scope of the current document, but a separate process in the browser.
The question is to have a ‘waiting’ indicator while a file is generated and then return to normal once the file is downloading. The way I like to do this is using a hidden iFrame and hook the frame’s onload event to let my page know when download starts. But onload does not fire in Internet Explorer for file downloads (like with the attachment header token). Polling the server works, but I dislike the extra complexity. So here is what I do: Target the hidden iFrame as usual. Generate the content. Cache it with an absolute timeout in 2 minutes. Send a JavaScript redirect back to the calling client, essentially calling the generator page a second time. Note: this will cause the onload event to fire in Internet Explorer because it's acting like a regular page. Remove the content from the cache and send it to the client. Disclaimer: Don’t do this on a busy site, because the caching could add up. But really, if your sites are that busy, the long running process will starve you of threads anyway. Here is what the code-behind looks like, which is all you really need. public partial class Download : System.Web.UI.Page { protected System.Web.UI.HtmlControls.HtmlControl Body; protected void Page_Load( object sender, EventArgs e ) { byte[ ] data; string reportKey = Session.SessionID + "_Report"; // Check is this page request to generate the content // or return the content (data query string defined) if ( Request.QueryString[ "data" ] != null ) { // Get the data and remove the cache data = Cache[ reportKey ] as byte[ ]; Cache.Remove( reportKey ); if ( data == null ) // send the user some information Response.Write( "Javascript to tell user there was a problem." ); else { Response.CacheControl = "no-cache"; Response.AppendHeader( "Pragma", "no-cache" ); Response.Buffer = true; Response.AppendHeader( "content-disposition", "attachment; filename=Report.pdf" ); Response.AppendHeader( "content-size", data.Length.ToString( ) ); Response.BinaryWrite( data ); } Response.End(); } else { // Generate the data here. I am loading a file just for an example using ( System.IO.FileStream stream = new System.IO.FileStream( #"C:\1.pdf", System.IO.FileMode.Open ) ) using ( System.IO.BinaryReader reader = new System.IO.BinaryReader( stream ) ) { data = new byte[ reader.BaseStream.Length ]; reader.Read( data, 0, data.Length ); } // Store the content for retrieval Cache.Insert( reportKey, data, null, DateTime.Now.AddMinutes( 5 ), TimeSpan.Zero ); // This is the key bit that tells the frame to reload this page // and start downloading the content. NOTE: Url has a query string // value, so that the content isn't generated again. Body.Attributes.Add("onload", "window.location = 'binary.aspx?data=t'"); } }
A quick solution if you only want to display a message or a loader GIF image until the download dialog is displayed is to put the message in a hidden container and when you click on the button that generate the file to be downloaded, you make the container visible. Then use jQuery or JavaScript to catch the focusout event of the button to hide the container that contain the message.
If XMLHttpRequest with a blob is not an option then you can open your file in a new window and check if any elements get populated in that window body with interval. var form = document.getElementById("frmDownlaod"); form.setAttribute("action", "downoad/url"); form.setAttribute("target", "downlaod"); var exportwindow = window.open("", "downlaod", "width=800,height=600,resizable=yes"); form.submit(); var responseInterval = setInterval(function() { var winBody = exportwindow.document.body if(winBody.hasChildNodes()) // Or 'downoad/url' === exportwindow.document.location.href { clearInterval(responseInterval); // Do your work. // If there is an error page configured in your application // for failed requests, check for those DOM elements. } }, 1000) // Better if you specify the maximum number of intervals
This Java/Spring example detects the end of a download, at which point it hides the "Loading..." indicator. Approach: On the JavaScript side, set a cookie with a maximum expiration age of 2 minutes, and poll every second for cookie expiration. Then the server-side overrides this cookie with an earlier expiration age -- the completion of the server process. As soon as the cookie expiration is detected in the JavaScript polling, "Loading..." is hidden. JavaScript Side function buttonClick() { // Suppose this is the handler for the button that starts $("#loadingProgressOverlay").show(); // Show loading animation startDownloadChecker("loadingProgressOverlay", 120); // Here you launch the download URL... window.location.href = "myapp.com/myapp/download"; } // This JavaScript function detects the end of a download. // It does timed polling for a non-expired Cookie, initially set on the // client-side with a default max age of 2 min., // but then overridden on the server-side with an *earlier* expiration age // (the completion of the server operation) and sent in the response. // Either the JavaScript timer detects the expired cookie earlier than 2 min. // (coming from the server), or the initial JavaScript-created cookie expires after 2 min. function startDownloadChecker(imageId, timeout) { var cookieName = "ServerProcessCompleteChecker"; // Name of the cookie which is set and later overridden on the server var downloadTimer = 0; // Reference to the timer object // The cookie is initially set on the client-side with a specified default timeout age (2 min. in our application) // It will be overridden on the server side with a new (earlier) expiration age (the completion of the server operation), // or auto-expire after 2 min. setCookie(cookieName, 0, timeout); // Set a timer to check for the cookie every second downloadTimer = window.setInterval(function () { var cookie = getCookie(cookieName); // If cookie expired (NOTE: this is equivalent to cookie "doesn't exist"), then clear "Loading..." and stop polling if ((typeof cookie === 'undefined')) { $("#" + imageId).hide(); window.clearInterval(downloadTimer); } }, 1000); // Every second } // These are helper JavaScript functions for setting and retrieving a Cookie function setCookie(name, value, expiresInSeconds) { var exdate = new Date(); exdate.setTime(exdate.getTime() + expiresInSeconds * 1000); var c_value = escape(value) + ((expiresInSeconds == null) ? "" : "; expires=" + exdate.toUTCString()); document.cookie = name + "=" + c_value + '; path=/'; } function getCookie(name) { var parts = document.cookie.split(name + "="); if (parts.length == 2 ) { return parts.pop().split(";").shift(); } } Java/Spring Server Side #RequestMapping("/download") public String download(HttpServletRequest request, HttpServletResponse response) throws Exception { //... Some logic for downloading, returning a result ... // Create a Cookie that will override the JavaScript-created // Max-Age-2min Cookie with an earlier expiration (same name) Cookie myCookie = new Cookie("ServerProcessCompleteChecker", "-1"); myCookie.setMaxAge(0); // This is immediate expiration, but can also // add +3 seconds for any flushing concerns myCookie.setPath("/"); response.addCookie(myCookie); //... -- presumably the download is writing to the Output Stream... return null; }
PrimeFaces uses cookie polling, too. monitorDownload(): monitorDownload: function(start, complete, monitorKey) { if(this.cookiesEnabled()) { if(start) { start(); } var cookieName = monitorKey ? 'primefaces.download_' + monitorKey : 'primefaces.download'; window.downloadMonitor = setInterval(function() { var downloadComplete = PrimeFaces.getCookie(cookieName); if(downloadComplete === 'true') { if(complete) { complete(); } clearInterval(window.downloadMonitor); PrimeFaces.setCookie(cookieName, null); } }, 1000); } },
I have updated the below reference code. Add a proper download URL link and try this out. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style type="text/css"> body { padding: 0; margin: 0; } svg:not(:root) { display: block; } .playable-code { background-color: #F4F7F8; border: none; border-left: 6px solid #558ABB; border-width: medium medium medium 6px; color: #4D4E53; height: 100px; width: 90%; padding: 10px 10px 0; } .playable-canvas { border: 1px solid #4D4E53; border-radius: 2px; } .playable-buttons { text-align: right; width: 90%; padding: 5px 10px 5px 26px; } </style> <style type="text/css"> .event-log { width: 25rem; height: 4rem; border: 1px solid black; margin: .5rem; padding: .2rem; } input { width: 11rem; margin: .5rem; } </style> <title>XMLHttpRequest: progress event - Live_example - code sample</title> </head> <body> <div class="controls"> <input class="xhr success" type="button" name="xhr" value="Click to start XHR (success)" /> <input class="xhr error" type="button" name="xhr" value="Click to start XHR (error)" /> <input class="xhr abort" type="button" name="xhr" value="Click to start XHR (abort)" /> </div> <textarea readonly class="event-log"></textarea> <script> const xhrButtonSuccess = document.querySelector('.xhr.success'); const xhrButtonError = document.querySelector('.xhr.error'); const xhrButtonAbort = document.querySelector('.xhr.abort'); const log = document.querySelector('.event-log'); function handleEvent(e) { if (e.type == 'progress') { log.textContent = log.textContent + `${e.type}: ${e.loaded} bytes transferred Received ${event.loaded} of ${event.total}\n`; } else if (e.type == 'loadstart') { log.textContent = log.textContent + `${e.type}: started\n`; } else if (e.type == 'error') { log.textContent = log.textContent + `${e.type}: error\n`; } else if (e.type == 'loadend') { log.textContent = log.textContent + `${e.type}: completed\n`; } } function addListeners(xhr) { xhr.addEventListener('loadstart', handleEvent); xhr.addEventListener('load', handleEvent); xhr.addEventListener('loadend', handleEvent); xhr.addEventListener('progress', handleEvent); xhr.addEventListener('error', handleEvent); xhr.addEventListener('abort', handleEvent); } function runXHR(url) { log.textContent = ''; const xhr = new XMLHttpRequest(); var request = new XMLHttpRequest(); addListeners(request); request.open('GET', url, true); request.responseType = 'blob'; request.onload = function (e) { var data = request.response; var blobUrl = window.URL.createObjectURL(data); var downloadLink = document.createElement('a'); downloadLink.href = blobUrl; downloadLink.download = 'download.zip'; downloadLink.click(); }; request.send(); return request } xhrButtonSuccess.addEventListener('click', () => { runXHR('https://abbbbbc.com/download.zip'); }); xhrButtonError.addEventListener('click', () => { runXHR('http://i-dont-exist'); }); xhrButtonAbort.addEventListener('click', () => { runXHR('https://raw.githubusercontent.com/mdn/content/main/files/en-us/_wikihistory.json').abort(); }); </script> </body> </html> Return to post Reference: XMLHttpRequest: progress event, Live example
Create an iframe when a button/link is clicked and append this to body. $('<iframe />') .attr('src', url) .attr('id', 'iframe_download_report') .hide() .appendTo('body'); Create an iframe with a delay and delete it after download. var triggerDelay = 100; var cleaningDelay = 20000; var that = this; setTimeout(function() { var frame = $('<iframe style="width:1px; height:1px;" class="multi-download-frame"></iframe>'); frame.attr('src', url + "?" + "Content-Disposition: attachment ; filename=" + that.model.get('fileName')); $(ev.target).after(frame); setTimeout(function() { frame.remove(); }, cleaningDelay); }, triggerDelay);
Capturing refresh on haskell websockets example server?
The websockets server example works as expected. On browser refresh (e.g. S-F5 with chrome), the websocket disconnects, still working as expected. After refresh, the user has to give name again to connect to the server. How would you capture the refresh-event and keep the user connected? E.g. Is this doable only on server side or does the client require modifications as well? Haskell examples or links to such would be nice as well as hints on how to do this!
How would you capture the refresh-event... There isn't really such a thing as a refresh event to detect (I would love to be proved wrong in this!) ... and keep the user connected... The refresh, or rather, the leaving of the page before loading it again, causes the websocket to disconnect, and (especially if this is the only page on the site that is open), there isn't really much you can do about it. So the only thing that can be done, is have some sort of auto-reconnect the next time the page loads. A solution that allows this is one where.. when the name is initially entered, the name is saved somewhere in the browser; when the page reloads, it checks for a previously saved name; and if it's found, it connects again using that name. Local storage is one such place to save this, as in the below example, modified from https://github.com/jaspervdj/websockets/tree/master/example to save/retrieve the name from local storage. $(document).ready(function () { var savedUser = sessionStorage.getItem("rejoin-user"); if (savedUser) { joinChat(savedUser); } $('#join-form').submit(function () { joinChat($('#user').val()) }); function joinChat(user) { sessionStorage.setItem("rejoin-user", user); $('#warnings').html(''); var ws = createChatSocket(); ws.onopen = function() { ws.send('Hi! I am ' + user); }; ws.onmessage = function(event) { if(event.data.match('^Welcome! Users: ')) { /* Calculate the list of initial users */ var str = event.data.replace(/^Welcome! Users: /, ''); if(str != "") { users = str.split(", "); refreshUsers(); } $('#join-section').hide(); $('#chat-section').show(); $('#users-section').show(); ws.onmessage = onMessage; $('#message-form').submit(function () { var text = $('#text').val(); ws.send(text); $('#text').val(''); return false; }); } else { $('#warnings').append(event.data); ws.close(); } }; $('#join').append('Connecting...'); return false; }; }); ... Is this doable only on server side or does the client require modifications as well? It definitely needs something done in the client to auto-reconnect. The bare bones version above needs no changes to the server, but if you wanted something fancier, like having the cases of initial connect and auto reconnect handled/shown differently somehow, then the server might need to be modified.
Add password to PDF's automatically
I'm currently using this code to just get an alert in the print dialog box (function() { var beforePrint = function() { alert('Functionality to run before printing.'); }; var afterPrint = function() { alert('Functionality to run after printing'); }; if (window.matchMedia) { var mediaQueryList = window.matchMedia('print'); mediaQueryList.addListener(function(mql) { if (mql.matches) { beforePrint(); } else { afterPrint(); } }); } window.onbeforeprint = beforePrint; window.onafterprint = afterPrint; }()); Everything works, I get an alert before and after the print dialog box shows. Now my problem is, or what I wanted to do, is to automatically secure saved pdf with passwords like I will set a random password in the script and the pdf will automatically be secured with that password. Is that even possible? Thank you in advance.
It is not possible to secure PDF using client side javascript. Your options are: secure pdf file on server using server-side library that can take existing pdf and apply a password to it; if you can regenerate PDF then you may try to implement javascript code (inside PDF) to check for passwords. This method is less secure because it relies on your own code and not utilizing PDF format built-in security features (and encryption);
Intercept new downloads in Firefox Addon SDK
I have written a simple download manager for Windows and I would like to create an addon for Firefox that when enabled intercepts new downloads in Firefox and sends them to the download manager. I have already done this for Google Chrome using: chrome.downloads.onCreated.addListener(function(details) { // stop the download chrome.downloads.cancel(details.id, null); } The question is how can I achieve something similar using the Firefox add-on SDK. I see there is a way of intercepting page loads to view the content / headers which might be helpful but then I won't know if the request will turn into a download or not. Firefox add-on SDK: Get http response headers I could perhaps look for a content type that is not text/html or check for a content disposition header but that could cause problems if I don't correctly handle all cases. Is there no way of accessing the download manager using the JS SDK or some way of knowing when a download has been started / being started and stop it?
The http-on-examine-response observer that the linked question discusses is the wrong way to go. It concerns all requests not just downloads. Instead use the Downloads.jsm to observe new downloads, then cancel them, and so on. To load Downloads.jsm in the SDK use: const {Cu} = require("chrome"); Cu.import("resource://gre/modules/Downloads.jsm"); Cu.import("resource://gre/modules/Task.jsm"); Then you can add your listener. let view = { onDownloadAdded: function(download) { console.log("Added", download); }, onDownloadChanged: function(download) { console.log("Changed", download); }, onDownloadRemoved: function(download) { console.log("Removed", download); } }; Task.spawn(function() { try { let list = yield Downloads.getList(Downloads.ALL); yield list.addView(view); } catch (ex) { console.error(ex); } }); The linked MDN docs have more information and samples. Since your add-on is a restartless SDK add-on, you'll need to remove the listener again using .removeView on unload, or else there will be a memory leak.
Here's the JSM way. Components.utils.import("resource://gre/modules/Downloads.jsm"); Components.utils.import("resource://gre/modules/Task.jsm"); Components.utils.import("resource://gre/modules/FileUtils.jsm"); var view = { onDownloadChanged: function (download) { console.log(download, 'Changed'); if (download.succeeded) { var file = new FileUtils.File(this.target.path); console.log('file', file); } } }; var list; Task.spawn(function () { list = yield Downloads.getList(Downloads.ALL); list.addView(view); }).then(null, Components.utils.reportError); Remember to removeView to stop listening. Can do this anywhere, like in shutdown function or whatever, doesn't have to be within that Task.spawn so list must be global var. list.removeView(view); //to stop listening Here's the old way, which seems to still work. Although I thought they said they're going to take out the old downloadManager: var observerService = Components.classes["#mozilla.org/download-manager;1"].getService(Components.interfaces.nsIDownloadManager); observerService.addListener({ onDownloadStateChange: function (state, dl) { console.log('dl=', dl); console.log('state=', state); console.log('targetFile', dl.targetFile); if (state == 7 && dl.targetFile.leafName.substr(-4) == ".txt") { //guys just downloaded (succesfully) a .txt file } } }); Heres a mozillazine with some more on this: http://forums.mozillazine.org/viewtopic.php?f=19&t=2792021