A cross-browser alternative to Canvas2Image or HTML5 download attribute? - javascript

While developing a pattern generator I am running into the same problem described in this question from 2011.
The answers given don't really offer a cross-browser, client-side solution.
I would accept any of the following solutions when clicking the Export Pattern button:
Triggering a download through canvas2image while ensuring that the file is saved with a .png extension (no matter what the filename is set to) or,
Display a widget (KendoUI preferably) with the image resulting from the Canvas2Image.saveAsPNG() method and let the user save it from there preferably not using the lame right-click solution, but with a link or a button.
HTML for the button I'm currently using:
<button id="downloadbtn" onClick="javascript:downloadImage()" data-role="button" class="k-button">Export Pattern</button>
Function that triggers the download:
function downloadImage () {
//...extra code omitted
var oCanvas = document.getElementById("my_canvas");
oCanvas.width = $("#pixels-h").val();
oCanvas.height = $("#pixels-v").val();
Canvas2Image.saveAsPNG(oCanvas);
//...extra code omitted
}
The file seems to download fine under OSX with Chrome Version 23.0.1271.95 and Safari Version 5.1.7 (6534.57.2).
I have a report of someone unable to open the file after downloading it under Firefox 17.0.1 for OSX. Apparently the download generates a .part file.
The biggest issue is that without a file extension I doubt that this method can be reliable.
I am looking for a client-side only solution with the widest possible compatibility with current browsers, so I guess the HTML5 download attribute would not do the trick as it is currently only supported in Chrome.
Any creative solutions?

I ran into the same issue. The basic problem is the filename needs to be added in the header but canvas2images uses document.location.href = strData and strData doesnt have headers. So the answer is, canvas2image does not support the feature we need, and we will need to try another solution. (for example perhaps FileSaver.js and canvas-toBlob.js)
http://eligrey.com/demos/FileSaver.js/

Related

Save a file on the harddrive with javascript

I have the following problem:
We are currently using a script to export data from CAD assemblies. This script is running in the Creo browser, which is currently IE. To access the correct directory the following code is used:
var fso = new ActiveXObject("Scripting.FileSystemObject");
var f = fso.CreateTextFile(session.GetCurrentDirectory() + ComponentName + ".xml", true);
f.Write(iht.join("\n"));
f.Close();
The Creo bowser is going to be switched to Chrome. Because of this ActiveX is no longer going to work. Is there a way to archive the same result with different code in Chrome?
Creo is not supporting Chrome Plugins, so IE Tab is not an option.
Any help is greatly appreciated!!
There is a non-standard feature:
https://developer.mozilla.org/en-US/docs/Web/API/FileSystem
But again, it is non-standard.
Edit: as written in that link, "This interface will not grant you access to the users filesystem. Instead you will have a "virtual drive" within the browser sandbox."
No. No more ActiveX.
In the past, most (auto)CAD programs came with a builtin LISP editor you could write scripts in. Maybe that is usable to rewrite the export if you find a LISP programmer.
Myself, I would install node.js on a server so you can use their file system module, which is a good replacement for the old active x object. This probably will require you to copy the files to that server though, so your current workflow might change a bit.

HTML/JS github pages project doesn't load images or sounds when run with firefox

Alright so this is a weird one, I'm not entirely sure if this is the right SE site, but I think it is because it regards web code/browser compatibility. If not, someone tell me in the comments I'll move it.
So basically, I have my game's source code on github. I also am hosting the game itself on github pages. This game should (I believe) function on Firefox and Chrome browsers. The source code has nothing unique to either browser.
The game runs fine on chrome. However, on Firefox this is not the case. None of the assets (images, sounds) are showing up/working on the github pages link. The weird thing is this though: on my local file system, when I open the html file with FF it runs/renders the assets just fine. Also, when I download the zip of my project and try it w/ FF, it also works fine. Why is this the case?
(Note, if you want to see the problem, click on the github pages link, then click on "Start Game", this will open it up to the game where the problem is occuring)
Edit:
Forgot to mention, the error I get in the FF console is NS_ERROR_NOT_AVAILABLE: it leads to line 421 which is this: g2d.drawImage(playerSprite, spriteLoc[0], spriteLoc[1]); where I draw the image onto the canvas. g2d is supposed to be ctx btw, thats a bad java habbit.
try changing the path of the resources.
you call the sound files, and image files this way:
laserSound = new Audio("resources\\Sounds\\laserblast.wav");
playerSprite.src = "resources\\Sprites\\Sprite.png";
you need to change the path to this:
laserSound = new Audio("resources/Sounds/laserblast.wav");
playerSprite.src = "resources/Sprites/Sprite.png";
that is change this \ to this /
the current way you are getting it, Firefox does not find where you files are at.
also, why dont you put init(); at the bottom of the JS file, its just to make sure, that the JS parser already knows that certain functions you will be calling are defined, like update() and initBackground() (this does not seem to be a problem, but just to be on the safe side.)

Cross-browser Save As .txt

Is there a JavaScript library that allows to save strings as txt files, and works cross-browser?
In the past, I have been using Downloadify, but I am looking at another option for a couple reasons:
I hope to find a pure JavaScript solution, without the need for Flash
it seems that Downloadify is not updated anymore
(no update in the past 18 months)
I am experiencing an issue with Downloadify in IE 9, where strings are cut off
Here is what you need. But it's not cross-browser yet. Works in Google Chrome.
<a download="MyFile.txt"
href="your-data-uri-here"
draggable="true"
class="dragout"
>Download ready</a>
Also Wikipedia has a good article about Data URI
As far as I know, the only way is to use data: URLs to force a download:
var data = "This is a test";
window.location.href = "data:application/x-download;charset=utf-8," + encodeURIComponent(data);
Two catches here:
It won't work in MSIE because its support of data: URLs is very limited (supposedly for security reasons). So you will still need Downloadify there.
You cannot specify a file name, the suggested file name will depend on the browser used. And file type will be "unknown" (you cannot use a known MIME type because the browser won't offer to download the file then).
Bonus reading: there was a W3.org discussion in February 2010 on fixing the second problem: http://lists.w3.org/Archives/Public/uri/2010Feb/thread.html#msg58. However, this doesn't seem to have made it into any specification so far, let alone browser implementations.
FileSaver API is cross-browser compatible
var text = "Hello, world!";
var blob = new Blob([text], {type: "text/plain;charset=utf-8"});
FileSaver.saveAs(blob, "filename.txt");

Detect version of the plugin in Chrome browser

I have NPAPI plugin and I want to detect its version before I embed it into web page. If version is not the latest one I want to show some message that asks users to update the plugin.
Now it's implemented in the following way
if (navigator.mimeTypes && navigator.mimeTypes["application/myplugin"]) {
{
// some code here
if(navigator.plugins["myplugin"] && navigator.plugins["myplugin"].version >= latest_version) {
// we have the latest version (embed the plugin into web page)
document.write ("<object id='plugin'><embed ....></object>");
} else {
document.write ("Show message here");
}
// some code
}
The problem is that navigator.plugins["myplugin"].version works fine in Firefox but not in Chrome. Chrome doesn't expose version property. I can add my own property in NPAPI code, but I don't see the way I can use it before embedding the plugin into page.
Is there any workaround?
Thanks in advance, Andrew
I see a lot of plugins have version information in either the name or the description. You should be able to access that information before the embed.
I actually put the version number in the filename, rather than even the name or description. The reason for this is that if there are multiple plugins with the same name, description, and mimetypes Firefox will generally use the latest version. Older versions of firefox have been inconsistent in how they handle this, so I even usually put the np???_version.dll file in a version-specific subdirectory.
It is a little bit of a pain, but it works consistently the same way in every NPAPI browser.
You can create a JSAPI property of your plugin containing the version. This property returns the plugin's version when called from javascript. So when you try to insert/embed the plugin in the page, you can check through javascript to make the appropriate calls.

Embedding image in QWebView with JavaScript

I am writing a small application with Qt 4.6 (64-bit Arch Linux, though that shouldn't matter) which lets the user edit a document using a QWebView with contentEditable turned on. However, for some reason embedding an image does not work. Here is a code snippet:
void LeafEditView::onInsertImage()
{
// bring up a dialog, ask for an image
QString imagePath = QFileDialog::getOpenFileName(this,tr("Open Image File"),"/",tr("Images (*.png *.xpm *.jpg)"));
ui->leafEditor->page()->mainFrame()->documentElement().evaluateJavaScript("document.execCommand('insertImage',null,'"+imagePath+"');");
}
The test image does in fact exist and yet absolutely nothing happens. Bold / italics / underline all work fine via JavaScript, just not images. Thoughts?
Check that QWebSettings::AutoLoadImages is enabled.
You could also try:
document.execCommand('insertImage',false,'"+imagePath+"');
Try using relative vs absolute paths to the image.
Last but not least, poke around this sample application -- they are using a similar method of Javascript execCommand(), they do some things in a slightly different way such as using QUrl::fromLocalFile.
Best of luck!
It turns out that WebKit has a policy of not loading resources from the local filesystem without some massaging. In my code, I have a WebKit view which I'm using to edit leaves in a notebook. The following one-liner solved my issue:
ui->leafEditor->page()->mainFrame()->setHtml("<html><head></head><body></body></html>",QUrl("file:///"));
From what I gleaned by lurking around the WebKit mailing list archives, in order to load files from the local filesystem one must set the URI to be file:, and this does the job.

Categories