Why my chrome crash when downloading ISO image file by using XMLHttpRequest - javascript

As title, my target is to monitor download status(total file size&current load file size). So, I write a simple code to help. But there exist a strange situation that is my chrome crash when download ISO OS image file(not picture file!!!). Are there any wrong of my code? BTW, when I observe console log for total size file and current load size file. I can't realize where the loaded file exactly store location.(but it indeed progress...until load 1GB then crash!) Are there any one who knows that?
<body>
function TriggerProgressEvent() {
//var progressBar = document.getElementById('p');
var xhr = new XMLHttpRequest();
var x = document.createElement("PROGRESS");
console.log('Entering TriggerProgressEvent');
xhr.open('GET', 'http://127.0.0.1:8080/features/upload/en_windows_server_2012_r2_essentials_x64_dvd_2707177.iso',true);
xhr.send();
xhr.onprogress = function(event) {
if(event.lengthComputable) {
console.log(event.total);
console.log(event.loaded);
x.setAttribute("max", event.total);
x.setAttribute("value", event.loaded);
document.body.appendChild(x);
}
};
xhr.onloadend = function(event) {
//console.log(event.loaded);
x.setAttribute("value", event.loaded);
document.body.appendChild(x);
};
}
</script>
</body>

Related

chrome extensions building (HTML text to clipboard saver)

I am very far for Web development. I need a Chrome extension which will copy page root directory html text to clipboard.
There is single file which is doing this job, but it working very slowly.
I make extension which downloads the page html with text file. But I want just copy . And in exe application paste.
function copyTextToClipboard()
{
var copyFrom=document.documentElement.innerHTML;
var file = new Blob([copyFrom], {type: 'text/plain'});
var atag = document.createElement("a");
var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate()+' '+today.getHours()+today.getMinutes()+today.getSeconds();
atag.href=URL.createObjectURL(file);
atag.download=date+".txt";
atag.click();
atag.remove();
//console.log(date);
var t =setTimeout(function(){ copyTextToClipboard() },10000);
}
copyTextToClipboard();
Any suggestion?
I found solutation. This code copying html file, in txt format every 5 second.
function copyTextToClipboard()
{
var copyFrom=document.documentElement.innerText;
if(copyFrom!=null)
{
var area = document.createElement("textarea");
area.value=copyFrom;
document.body.appendChild(area);
area.select();
document.execCommand('copy');
document.body.removeChild(area);
}
var t =setTimeout(function(){ copyTextToClipboard() },5000);
}
copyTextToClipboard();

"Not allowed to navigate top frame to data URL" when downloading canvas in javascript

In my website, I am trying to download tainted canvases that I have created. I get the "Not allowed to navigate top frame to data URL:" (followed with a string of data) when I try to do this.
I have looked at other posts about this and they are generally trying to show their canvas or something else instead of saving the canvas.
Here is my code:
//it looks complicated, but the only important lines are the ones before the else statement,
function download_img(el) {
//the if statement is used to see if this is using the canvas or not
if(document.getElementById("canvasImage").style.display != "none"){
alert('canvas')
var canvImg = document.getElementById("canvasImage").toDataURL("image/jpg");
el.href = canvImg;
}else{
//again, this code is for the image side of the project, which works fine
alert('image')
var xhr = new XMLHttpRequest();
xhr.open("GET", document.getElementById("theImg").src, true);
xhr.responseType = "blob";
xhr.onload = function(){
var urlCreator = window.URL || window.webkitURL;
var imageUrl = urlCreator.createObjectURL(this.response);
var tag = document.createElement('a');
tag.href = imageUrl;
tag.download = "meme";
document.body.appendChild(tag);
tag.click();
document.body.removeChild(tag);
}
xhr.send();
}
}
My HTML:
<a style="float:left;display:inline;" href="" onclick="download_img(this)">Canvas Button</a>
What I want to happen is that the canvas is saved.
Add the download attribute to the <a> tag to force it to download instead of navigate.

How to generate and download multiple files at once with javascript (jsPdf) and firefox?

I'm using JsPDF to generate a number of PDF files and then download them. With Chrome and Edge it's correctly generating and downloading all of them, but with Firefox is downloading only the first one.
This is my code:
<script>
$( document ).ready(function() {
let doc = new jsPDF();
doc.text(20, 20, 'hello');
for(a = 0; a < 6; a++){
// doc.output('dataurlnewwindow'); < NOT WORKING ON RECENT BROWERS.
// doc.output('datauri');
// doc.addHTML($('#content'), 1, 1, function () {
// var blob = doc.output("blob");
// window.open(URL.createObjectURL(blob));
// });
doc.save('file_number_' + 'a' + '.pdf'); < DOWNLOADS ONLY THE FIRST FILE IN FIREFOX.
}
});
</script>
How could I be able to download all the generated files? It would be OK even if I could open them in a new window, as long as I'm able to specify the filename of the PDF.
Thanks in advance.
Edit: as indicated by pytness, it appears Firefox is blocking the process.
I just tried to delay the clicks in this way:
function clickAll(){
let waiter = 0;
$('.pdf_line').each(
function(){
if ($(this).find('input').prop('checked')){
//console.log('click! waiter = ' + waiter);
$(this).find('.print_document').delay(4000*waiter).click();
waiter++;
};
}
)
}
But after the first download Firefox halts the whole process.
It looks like you’re saving the file with the same name every time in your loop, so it’s just saving over it each time. Try changing the ‘a’ in your doc.save to a

Why does Safari's document.adoptNode() convert css class names to lowercase when source document is in quirks mode?

I am using XHR (XML Http Request) to load an html fragment. I am using responseType = "document" in order to offload the html parsing to the browser. When the ajax call completes, I am using document.adoptNode() to include the ajax html elements in my main document.
I noticed a weird bug that affects Safari only (v9.1.1 on El Capitan and iOS 9.3.2). It seems that when Safari adopts the node, it will convert css class names into lower case. For a full demonstration, see this jsfiddle: https://jsfiddle.net/theblueslate/wxo7zst5/2/
This bug doesn't occur on Chrome v51 or IE11.
The code from the jsfiddle is included here:
function buildDataLoadedCallback (containerId, useAdopt) {
return function() {
var parsedDoc = this.response;
var parsedBodyChild = parsedDoc.body.children[0];
var newNode;
if (useAdopt) {
newNode = document.adoptNode(parsedBodyChild);
} else {
newNode = document.importNode(parsedBodyChild, true);
}
var container = document.getElementById(containerId);
container.appendChild(newNode);
}
}
function requestAjaxHtmlFragment(pageName, callback) {
var xhr = new XMLHttpRequest();
xhr.responseType = "document";
xhr.addEventListener("load", callback);
/* this fragment.html file simply contains:
<div class="myClass">
<p>MyClass</p>
</div>
*/
xhr.open("GET","https://dl.dropboxusercontent.com/u/15211879/js-fiddle/" + pageName + ".html", /*async:*/true);
xhr.send();
}
var pageName = "fragment";
requestAjaxHtmlFragment(pageName, buildDataLoadedCallback(pageName + "-adopt-container", true));
Is there an obvious error that I am missing? I can't spot it, and I have raised a webkit bug: https://bugs.webkit.org/show_bug.cgi?id=159555, but I am hoping I am wrong.
Turns out this was a bug. Now fixed in WebKit: https://bugs.webkit.org/show_bug.cgi?id=159555
I think it is still useful posting this to SO. Posting increases the visibility for anybody else who is struggling with this issue, as I was.

How can I call revokeObjectURL only after the URL has loaded?

I have a web application. It runs in Google Chrome and is not required to work in any other browser.
I have PDF data which has been generated on the server and sent back to the client in an AJAX request.
I create a blob from the PDF data.
I use window.URL.createObjectURL to create a URL from the blob, which I then load into a window (my preview_window) which has previously been created to show the PDF.
To load the URL, I set preview_window.location.href.
I would like to call revokeObjectURL to avoid wasting more and more resources as new PDFs are generated and previewed in the window.
The problem is that calling it immediately after setting preview_window.location.href is too soon, and stops the PDF from being displayed. So I would like to call revokeObjectURL only once the URL has been loaded.
I have tried setting preview_window.onload to a callback for this purpose, but it never gets called.
I would like to know:
Is it possible to trigger a callback when the window has loaded the URL, as I am trying to do? How?
Is there another approach to ensure revokeObjectURL gets called in a timely manner?
If I cannot trigger revokeObjectURL when the window finishes loading the URL, I may revoke each URL immediately before generating a new one. But I would rather revoke the URL as soon as it is done loading, if possible.
I have prepared a html file which demonstrates the situation pretty well:
<html>
<head>
<title>Show PDF Demo</title>
<script>
var build_blob = function(mime_type, data) {
var buf = new ArrayBuffer(data.length);
var ia = new Uint8Array(buf);
for (var i = 0; i < data.length; i++) ia[i] = data.charCodeAt(i);
var blob = new Blob([ buf ], { type: mime_type });
return blob;
};
window.onload = function(e) {
document.getElementById('preview_button').onclick = function(e) {
// open the window in the onclick handler so we don't trigger popup blocking
var preview_window = window.open(null, 'preview_window');
// use setTimeout to simulate an asynchronous AJAX request
setTimeout(function(e) {
var pdf_data = atob(
"JVBERi0xLjQKMSAwIG9iago8PCAvVHlwZSAvQ2F0YWxvZwovT3V0bGluZXMgMiAwIFIKL1BhZ2Vz" +
"IDMgMCBSCj4+CmVuZG9iagoyIDAgb2JqCjw8IC9UeXBlIC9PdXRsaW5lcwovQ291bnQgMAo+Pgpl" +
"bmRvYmoKMyAwIG9iago8PCAvVHlwZSAvUGFnZXMKL0tpZHMgWzQgMCBSXQovQ291bnQgMQo+Pgpl" +
"bmRvYmoKNCAwIG9iago8PCAvVHlwZSAvUGFnZQovUGFyZW50IDMgMCBSCi9NZWRpYUJveCBbMCAw" +
"IDUwMCAyMDBdCi9Db250ZW50cyA1IDAgUgovUmVzb3VyY2VzIDw8IC9Qcm9jU2V0IDYgMCBSCi9G" +
"b250IDw8IC9GMSA3IDAgUiA+Pgo+Pgo+PgplbmRvYmoKNSAwIG9iago8PCAvTGVuZ3RoIDczID4+" +
"CnN0cmVhbQpCVAovRjEgMjQgVGYKMTAwIDEwMCBUZAooU01BTEwgVEVTVCBQREYgRklMRSkgVGoK" +
"RVQKZW5kc3RyZWFtCmVuZG9iago2IDAgb2JqClsvUERGIC9UZXh0XQplbmRvYmoKNyAwIG9iago8" +
"PCAvVHlwZSAvRm9udAovU3VidHlwZSAvVHlwZTEKL05hbWUgL0YxCi9CYXNlRm9udCAvSGVsdmV0" +
"aWNhCi9FbmNvZGluZyAvTWFjUm9tYW5FbmNvZGluZwo+PgplbmRvYmoKeHJlZgowIDgKMDAwMDAw" +
"MDAwMCA2NTUzNSBmCjAwMDAwMDAwMDkgMDAwMDAgbgowMDAwMDAwMDc0IDAwMDAwIG4KMDAwMDAw" +
"MDEyMCAwMDAwMCBuCjAwMDAwMDAxNzkgMDAwMDAgbgowMDAwMDAwMzY0IDAwMDAwIG4KMDAwMDAw" +
"MDQ2NiAwMDAwMCBuCjAwMDAwMDA0OTYgMDAwMDAgbgp0cmFpbGVyCjw8IC9TaXplIDgKL1Jvb3Qg" +
"MSAwIFIKPj4Kc3RhcnR4cmVmCjYyNQolJUVPRg=="
);
/*
Warning: for my Chrome (Version 44.0.2403.155 m), the in-built PDF viewer doesn't seem
to work with a blob when this html page is loaded from the local filesystem. I have only
got this to work when fetching this page via HTTP.
*/
var pdf_blob = build_blob('application/pdf', pdf_data);
var pdf_url = window.URL.createObjectURL(pdf_blob);
preview_window.onload = function(e) {
console.log("preview_window.onload called"); // never happens
window.URL.revokeObjectURL(pdf_url);
};
preview_window.location.href = pdf_url;
console.log("preview_window.location.href set");
}, 500);
};
};
</script>
</head>
<body>
<button id="preview_button">Show Preview</button>
</body>
</html>
Although my demo code above avoids it, I do have jQuery loaded for my application, so if that makes things easier I'm open to using it.
I did find this question in a search, but in that situation the main window ("window") is pointed to a new URL, and the OP never got a response when asking in comments whether it makes a difference if the window came from window.open.
As you found out, you can't set open()ed windows' onload event from the opener.
You will have to inject some script in the second page that will call its window.opener functions.
But since you are opening a pdf file, the browser will re-parse entirely your page and your injected code will vanish.
The solution, as you found out yourself in the comments, is to inject the blob's url in an iframe, and wait for this iframe's load event.
Here is how :
index.html
<script>
// The callback that our pop-up will call when loaded
function imDone(url){
window.URL.revokeObjectURL(url);
}
var build_blob = function(mime_type, data) {
var buf = new ArrayBuffer(data.length);
var ia = new Uint8Array(buf);
for (var i = 0; i < data.length; i++) ia[i] = data.charCodeAt(i);
var blob = new Blob([ buf ], { type: mime_type });
return blob;
};
var preview_window=null;
window.onload = function(e) {
document.getElementById('preview_button').onclick = function(e) {
if(preview_window===null || preview_window.closed){
// open the window in the onclick handler so we don't trigger popup blocking
preview_window = window.open('html2.html', 'preview_window');
}
// avoid reopening the window since it may cache our last blob
else preview_window.focus();
// use setTimeout to simulate an asynchronous AJAX request
setTimeout(function(e) {
var pdf_data = /* Your pdf data */
var pdf_blob = build_blob('application/pdf', pdf_data);
var pdf_url = window.URL.createObjectURL(pdf_blob);
// Simple loop if our target document is not ready yet
var loopLoad = function(url){
var doc = preview_window.document;
if(doc){
var iframe = doc.querySelector('iframe');
if(iframe)iframe.src = url;
else setTimeout(function(){loopLoad(url);},200);
}
else setTimeout(function(){loopLoad(url);},200)
};
loopLoad(pdf_url);
}, 0);
};
};
</script>
and the html2.html
<html>
<head>
<title>Iframe PDF Demo</title>
<style>
body, html, iframe{margin:0; border:0}
</style>
</head>
<body>
<iframe width="100%" height="100%"></iframe>
<script>
document.querySelector('iframe').onload = function(){
//first check that our src is set
if(this.src.indexOf('blob')===0)
// then call index.html's callback
window.opener.imDone(this.src);
}
</script>
</body>
</html>
Live Demo

Categories