save web page source javascript - javascript

I want to save the source website by javascript and send them via socket, but I have a problem. Written string is badly formatted. Everything is in one line, so that javascript does not work.
I tried:
var html = document.documentElement.outerHTML; //document.outerHTML
var html = new XMLSerializer().serializeToString(document.documentElement);
var html = new XMLSerializer().serializeToString(document);
And I tried to encode to base64.
How to save a web page so that later work?

Related

Javascript store outputs and download file

I have a JavaScript app that calculates various values. I would like to have a function that stores calculated output values (e.g. when you click a "store value" button), creating a list in the background that the user could then download as, e.g., a text file. I'm wondering what the easiest implementation of this would be in the browser -- values can get wiped on page refresh so no need to store long-term. Thanks!
Are you asking for a way to download a file with these values?
Here is a quick example of how to do that:
Let's say I have an a-tag in my html like this
<a id="Button" download="download.txt">Download</a>
I can then use javascript to make it download a file with text in it
Button = document.getElementById('Button');
theText="Hello";
var textFile = null,
makeTextFile = function (text) {
var data = new Blob([text], {type: 'text/plain'});
// If we are replacing a previously generated file we need to
// manually revoke the object URL to avoid memory leaks.
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
// returns a URL you can use as a href
return textFile;
};
Button.href=makeTextFile(theText);
Then when we click the link, it downloads a text file with the contents "Hello". I got this code from somewhere a really long time ago when I was working on a project, but I don't remember where it is from.
If this isn't what you are asking for, please clarify your question.

How do I recreate the original file using Javascript?

Working on a Javascript-based file encryption program. It works great for text files, but I'm trying to do other data (images, etc) and the decrypted file isn't matching. In my program, I use the following code to read the file that the user provides:
let reader = new FileReader();
let file = UI.file.input.files[0];
reader.readAsText(file, 'UTF-8');
The reader then adds that to a Javascript object that contains other information, like the date and file name. Then, that's stringified using JSON.stringify() and encrypted. When the encryption is completed, the file gets saved as a different file format with the encrypted JSON inside of it. The code for that is:
let message = // ENCRYPTED FILE STRING
let file = new Blob([message], {
type: 'text/plain'
});
let url = URL.createObjectURL(file);
The url is then attached to a link element on the page. That's all working fine.
To decrypt it, the file is again provided by the user and runs through the same reader as used above. It's decrypted successfully and the resulting string is again put into an object using JSON. Up to that point, it works exactly as it's supposed to. It works fine if what I'm decrypting is a text file, but if I do an image file it all goes bad.
To save the decrypted file, I use this code:
let message = // DECRYPTED DATA CONVERTED TO AN OBJECT
let fileName = message.name;
let fileType = message.type;
let file = new Blob([message.data], {
type: fileType
});
let url = URL.createObjectURL(file);
The original file and and original file type are both pulled from the file before it's encrypted and added to the object that has the file data. Like I said, there's no problem with the encryption or decryption process. I've used a HEX viewer to check and the string that is being put into the encryption process is identical to the one coming out. I'm guessing the issue is somewhere in my final block of code.
My best guess is something to do with encoding, although I'm not sure exactly what. Any help would be greatly appreciated.
You can use FileReader.readAsDataURL and strip the data:*/*;base64, from the string. Then you'll have a base64 encoded string that you can put into JSON.

How to take a snapshot of webpage from the url?

I want to take a snapshot of the webpage from the url. The url is an html web page which is dynamic. Basically we needed an img of that webpage.
I thought to convert the html page to image in c# but din't work.
I first read the html using streamreader and using NReco.ImageGenerator tried to convert into bytes and finally image. This isnt working.
Finally I am trying to convert html to canvas using javascript from inside the html web page.
function report() {
let region = document.querySelector("body");
html2canvas(
$('body'),
{allowTaint: true, logging: true,'onrendered': function (canvas)
{}}).then( //getting problem here at then
function (canvas) {
let jpgUrl = canvas.toDataURL();
console.log(jpgUrl);
var text = "bottom-right Brochure1";
var imageName = text + '.jpg';
download(jpgUrl,imageName, "image/png");
}
Code explained - It will take a snpashot of the body element in the html page using js. Take the url and create the canvas from the url. and automatically download. But i face a issue ------- " html2canvas(...),then is not a function" .. I dont know why its happening. Please help.
Because of Cross-Origin Resource Sharing (CORS) restrictions in all modern browsers, this can't be done purely on the clientside. You need something on the server-side to accomplish this. To do it in javascript on the server use NodeJS there are several npm packages that can help like: node-server-screenshot, PhantomJS etc

Creating download prompt using purely javascript

I have some text data (say var a = 'Hello World From Javascript';)in javascript variable in current window. I want to do the following
through javascript-
1. open a new window and write the text data to the window.
2. set the content type to text/plain.
3. set the content-disposition to attachment, so that download prompt comes.
4. user downloads the text data as a text file and saves it to his local disk.
is this all possible through javascript?
I know we can make ajax calls to server or redirect but in this case instead of following above steps. But in this case, these workarounds are not adaptable.
you can do that using JS & HTML5 features. Please find below a sample code.
var fileParts = ['Hello World From Javascript'];
// Create a blob object.
var bb = new Blob(fileParts,{type : 'text/plain'});
// Create a blob url for this.
var dnlnk = window.URL.createObjectURL(bb);
var currentLnk = $('#blobFl').attr('href');
// blobFl is the id of the anchor tag through which the download will be triggered.
$('#blobFl').attr('href',dnlnk);
$('#blobFl').attr('download','helloworld.txt');
// For some reason trigger from jquery dint work for me.
document.getElementById('blobFl').click();
Triggering a file download without any server request
Unfortunately this is not something you can do with normal browser capabilities. Something like flash or a browser-specific plugin will get you what you need, but security limitations within javascript will not let you download arbitrary data created within the browser.
Also the 'data' url is not supported across all browser/version combinations. I am not sure if your users are constrained on what browser they are using or not but that may limit what you can do with that solution.
Source: Triggering a file download without any server request
If you already have the file on the server (I make an ajax call to generate and save a PDF on the server) - you can do this
window.location.replace(fileUrl);
No, Content-Disposition is a response header, it has to come from the server. I think you could do it with Flash but I wouldn't recommend it.
Here's a clean, pure js version of #Rajagopalan Srinivasan's answer:
var fileParts = ["Hello World From Javascript"];
// The anchor tag to use.
const blobLink = document.getElementById("blobLink");
// Create a blob object.
var blob = new Blob(fileParts, { type: "text/plain" });
// Create a blob url for this.
var blobUrl = window.URL.createObjectURL(blob);
blobLink.setAttribute("href", blobUrl);
blobLink.setAttribute("download", "helloworld.txt");
blobLink.click();
<a id="blobLink">Download</a>

Base64 encode and image in Adobe Air

I am writing an Adobe Air app in HTML/JavaScript and I am trying to base64 encode an image so I can add it to and XML RPC request. I have tried many methods and nothing seems to work.
I see that actionscript has a Base64Encoder class that look like it would work, is there any way to utilize this in JavaScript?
Thanks #some for the link.
I used the btoa() function to base64 encode image data like this:
var loader = new air.URLLoader();
loader.dataFormat = air.URLLoaderDataFormat.BINARY;
loader.addEventListener(air.Event.COMPLETE,function(e){
var base64image = btoa(loader.data);
});
var req = new air.URLRequest('file://your_path_here');
loader.load(req);
I was trying to upload an image using metaWeblog.newMediaObject, but it turns out that the data doesn't need to be base64 encoded, so the binary value was all that was needed.

Categories

Resources