Access Language JSON file with JS on Chrome without a webserver - javascript

tl/dr: How can I
internationalize strings in a html5/javascript application
while using a json file or something similar with key/value pairs (easy to translate)
without using javascript vars for every language string (ugly)
and if possible, without complex frameworks or packages
on Chrome (or something with same-origin-policy)
without a (local) webserver
without internet connection
Details:
I am developing a html5 touch game for older useres on an embedded IE system that will be changed to an embedded chrome system soon. Using a webserver is currently no option and I can't assume I have an internet connection all the time. Since the application should be in different languages, I currently have a json file that is accessed like this (irrelevant stuff left out):
//...
var language = "en"; //the language we want, same as the json file name
var key = "key"; //the key to the value we like to obtain
var languageMap;
var langFile = $.getJSON(language + ".json", function(data){
languageMap = data;
});
var langFileStatus = $.when(langFile);
langFileStatus.done(function () {
var value = languageMap[key];
//use the value of "key" here for awsome stuff
});
//...
the language file (e.g. "en.json") looks like this:
{
"key":"value",
"otherKey":"otherValue",
}
which works pretty well for IE and FF, but not on Chrome, because of the same-origin-policy. I read about an awsome trick to bypass that here, but I couldn't make it work in this case. I have never used JSON before in connection with JS, so maybe its an easy question. Different solutions for the whole problem are also very welcome (thats why I posted the complete problem). Thanks in advance!

Download Web Server for Chrome App from here. This is not exactly a server, but a handy simulation of the same that allows you to run your files locally as if they are running on a server.
It works without any Internet connection. More importantly, it has configuration options for CORS request thanks to recent updates Install it, select the folder in which your files are present, and you are ready! It's a really good way to test your code locally on Chrome.

Related

The Basics needed for creating a map in D3js [duplicate]

I try to import a local .json-file using d3.json().
The file filename.json is stored in the same folder as my html file.
Yet the (json)-parameter is null.
d3.json("filename.json", function(json) {
root = json;
root.x0 = h / 2;
root.y0 = 0;});
. . .
}
My code is basically the same as in this d3.js example
If you're running in a browser, you cannot load local files.
But it's fairly easy to run a dev server, on the commandline, simply cd into the directory with your files, then:
python -m SimpleHTTPServer
(or python -m http.server using python 3)
Now in your browser, go to localhost:3000 (or :8000 or whatever is shown on the commandline).
The following used to work in older versions of d3:
var json = {"my": "json"};
d3.json(json, function(json) {
root = json;
root.x0 = h / 2;
root.y0 = 0;
});
In version d3.v5, you should do it as
d3.json("file.json").then(function(data){ console.log(data)});
Similarly, with csv and other file formats.
You can find more details at https://github.com/d3/d3/blob/master/CHANGES.md
Adding to the previous answers it's simpler to use an HTTP server provided by most Linux/ Mac machines (just by having python installed).
Run the following command in the root of your project
python -m SimpleHTTPServer
Then instead of accessing file://.....index.html open your browser on http://localhost:8080 or the port provided by running the server. This way will make the browser fetch all the files in your project without being blocked.
http://bl.ocks.org/eyaler/10586116
Refer to this code, this is reading from a file and creating a graph.
I also had the same problem, but later I figured out that the problem was in the json file I was using(an extra comma). If you are getting null here try printing the error you are getting, like this may be.
d3.json("filename.json", function(error, graph) {
alert(error)
})
This is working in firefox, in chrome somehow its not printing the error.
Loading a local csv or json file with (d3)js is not safe to do. They prevent you from doing it. There are some solutions to get it working though. The following line basically does not work (csv or json) because it is a local import:
d3.csv("path_to_your_csv", function(data) {console.log(data) });
Solution 1:
Disable the security in your browser
Different browsers have different security setting that you can disable. This solution can work and you can load your files. Disabling is however not advisable. It will make you vulnerable for all kind of threads. On the other hand, who is going to use your software if you tell them to manually disable the security?
Disable the security in Chrome:
--disable-web-security
--allow-file-access-from-files
Solution 2:
Load your csv/json file from a website.
This may seem like a weird solution but it will work. It is an easy fix but can be unpractical though. See here for an example. Check out the page-source. This is the idea:
d3.csv("https://path_to_your_csv", function(data) {console.log(data) });
Solution 3:
Start you own browser, with e.g. Python.
Such a browser does not include all kind of security checks. This may be a solution when you experiment with your code on your own machine. In many cases, this may not be the solution when you have users. This example will serve HTTP on port 8888 unless it is already taken:
python -m http.server 8888
python -m SimpleHTTPServer 8888 &
Open the (Chrome) browser address bar and type the underneath. This will open the index.html. In case you have a different name, type the path to that local HTML page.
localhost:8888
Solution 4:
Use local-host and CORS
You may can use local-host and CORS but the approach is not user-friendly coz setting up this, may not be so straightforward.
Solution 5:
Embed your data in the HTML file
I like this solution the most. Instead of loading your csv, you can write a script that embeds your data directly in the html. This will allow users use their favorite browser, and there are no security issues. This solution may not be so elegant because your html file can grow very hard depending on your data but it will work though. See here for an example. Check out the page-source.
Remove this line:
d3.csv("path_to_your_csv", function(data) { })
Replace with this:
var data =
[
$DATA_COMES_HERE$
]
You can't readily read local files, at least not in Chrome, and possibly not in other browsers either.
The simplest workaround is to simply include your JSON data in your script file and then simply get rid of your d3.json call and keep the code in the callback you pass to it.
Your code would then look like this:
json = { ... };
root = json;
root.x0 = h / 2;
root.y0 = 0;
...
I have used this
d3.json("graph.json", function(error, xyz) {
if (error) throw error;
// the rest of my d3 graph code here
}
so you can refer to your json file by using the variable xyz and graph is the name of my local json file
Use resource as local variable
var filename = {x0:0,y0:0};
//you can change different name for the function than json
d3.json = (x,cb)=>cb.call(null,x);
d3.json(filename, function(json) {
root = json;
root.x0 = h / 2;
root.y0 = 0;});
//...
}

Html5 audio tag not working in Local IIS for Google translate_tts

Trying to use google's translate_tts as my fallback if the browser doesn't support speechSynthesis for my project.
Now I am having some trouble with getting the html5 audio working properly.
Been scratching my head and googling all day on why it wasn't working for me.
Then I came across some articles/forums saying that it's something to do with IIS. So I did a test code outside my site to see what happens, and was surprised this worked properly! But when using the same code in my original project which is running in IIS it doesn't work. AND it works when using IIS EXPRESS. I check the MIME types in IIS and mpeg and mp3 are there.
Even doing it in javascript doesn't work in IIS.
TextToSpeech.Audio = document.createElement("AUDIO");
TextToSpeech.Audio.src = url;
TextToSpeech.Audio.playbackRate = 1;
TextToSpeech.Audio.preload = 'auto';
TextToSpeech.Audio.volume = 1; // 0 to 1;
TextToSpeech.Audio.addEventListener('ended', function () {
//i have some code here...
});
TextToSpeech.Audio.addEventListener('error', function (error) { });
TextToSpeech.Audio.play();
Has anyone encountered this issue and happened to resolve it? Your help will be much appreciated, Thanks!
UPDATE: After some more googling, this might be because I am calling it from within my site hosted in IIS which has a proper hostname and my IIS Express runs the site in localhost:PORT which Google sees as noreferrer?
starting some time in the last few days, google seems to have placed a 'captcha' on this service and made it so that it can no longer be called by a server. so this may all be moot.
it used to be you could ONLY call it as a noreferrer, so i don't think noreferrer is your issue (or may be the least of your issues starting a few days back). one way to workaround the issue in fact was to add ref='noreferrer' to your link.
and this may be your initial issue: using wget, you had to use the -U Mozilla option which makes wget appear to be a browser. if you called the url without that, it didn't return anything. so if there is a way to make your IIS look like a browser when calling the google url, that may work.
this link google text-to-speech artile still does work in a browser, maybe that will help you use it the way you want.
however... starting july 28th, i get a '503 service not available' after using it for years with wget on my linux server. could be because it's metered and i've overrused it... i hope it comes back on. i only use it about 100x/day.
they always said it was 'not public' but it is widely used that way...
so that could be related if you're still trying to call it from IIS which i would think behaves similarly to calling it from a linux server.

Deleting the file from client PC after upload but only after client permission

I got a requirement from client to delete file from his local pc after upload. It should ask to user if he want to delete the file after successful upload. If user opted yes then file should be deleted from client pc.
I know this is not easy to achieve in web application while quite easy in desktop app.My client is upgrading from desktop app to web and expecting the same behavior.
I heard that any browser plugin or small utility installed on client machine can do that. I have seen few example in other website that client is referring.
Can someone please suggest me the plugin or utility logic that can help me to achieve this? And how we can interact with these stuff from our java script or code.
Thanks in advance.
Regards,
Krishan
Javascript/HTML5 alone can't do this, it's restricted to maintain a certain level of security. You will have to look into activeX plugins, and it will only work if the user runs the web app on IE.
Here is a short example:
<script type="text/javascript">
// initialize ActiveXObject with Scripting.FileSystemObject:
var activeX_FileSystemObject = new ActiveXObject("Scripting.FileSystemObject");
if(confirm("Delete file?"))
{
activeX_FileSystemObject.DeleteFile("C:\\myFolder\\myFile.txt", true);
}
// Another way (multiple files in a catalog):
if(confirm("Delete file?"))
{
activeX_FileSystemObject.DeleteFile("C:\\myFolder\\*.txt", true);
}
activeX_FileSystemObject = null;
</script>
It's also possible that a Chrome plugin can do the same as the activeX, but never coded one myself - and it's also Chrome spesific.

Javascript Access to File on local machine

I want to open the files located on local drive using window.open().
When i try to access the file using window.open i am getting error "Access is denied."
Would somebody help to achieve this requirement in Internet explorer 8.0?
Thanks!
You can't. And thank God for that. Imagine how insecure the internet would've been if JS was able to access a client's file-system.
Of course, IE8 has the MS specific JScript superset (ActiveXObject), which does enable filesystem access:
var fileHandle,
fs = new ActiveXObject("Scripting.FileSystemObject");
fileHandle = fs.OpenTextFile("C:\\path\\to\\file.tmp", 1, true);
fileHandle.Write('This is written to a file');
console.log(fileHandle.ReadLine());//will log what we've just written to the file
But this is non-standard, is - I think- no longer supported either, and doesn't work X-browser.
Here's the documentation. At the bottom there's a link to a more detailed overview of the properties and methods this object has to offer, as you can see, there's a lot to choose from
I'm adding this answer just to be complete, but so far as Web Pages go, Elias Van Ootegem's answer is correct: you can't (and shouldn't be able to) get to the local hard drive.
But .. you can isf your page is an HTA (HTML Application) :
HTML Application wiki
This is essentially a web page with .hta as the extension(usually) and some extra tags to tell IE that it's an HTA application, not a web page.
This is something that runs via the windows operating system and is so far as I'm aware only available for IE. The HTA application opens as a web page in IE, but without the usual web navigation / favourites toolbars etc.
Note that if you have a page on an internet server delivered as an HTA application, you're likely to cause virus scanners and firewalls to pop up because this would essenstially be running a script whcih could do manything to your computer. Not good for general internert stuff at all, but might be useful in a secure environment like an intranet where the source of the application is known to be safe.
To get to the file system, you can use javascript code like this :
// set up a Fils System Object variable..
var FSO = new ActiveXObject("Scripting.FileSystemObject");
// function to read a file
function ReadFile(sFile) {
var f, ts;
var s="";
if(FSO.FileExists(sFile))
{
f = FSO.GetFile(sFile);
ts = f.OpenAsTextStream(ForReading, TristateUseDefault);
if (!ts.AtEndOfStream) {s = ts.ReadAll( )};
ts.Close( );
}
return s;
}
alert(ReadFile("c:\\somefilename.txt");

To Access Notepad, calculator through asp.net

I m trying to open Notepad, Calculator in button click in asp.net with code behind C#. I tried with the code
System.Diagnostics.Process.Start("c:\\windows\\system32\\notepad.exe");
this is working fine in local system but not working in the Server. I even tried with the javascript
function executeCommands(inputparms)
{
alert('ff');
var oShell = new ActiveXObject("Shell.Application");
var commandtoRun = "C:\\Winnt\\Notepad.exe";
if (inputparms != "")
{
var commandParms = document.form1.filename.value;
}
oShell.ShellExecute(commandtoRun, commandParms, "", "open", "1");
}
even this is not working out. Can you please suggest me in on how to open the notepad application in the client end with out disturbing server notepad.
This can't be done. Imagine the security mess we'd be in if a web-page could run arbitrary programs on a client machine. Oh wait... ;-)
This is not possible (in general, though you could possibly get around with with various applets and browser plugins). In fact, I would be quite mortified if any web page could execute an arbitrary program on my computer.
You cannot do this. ASP.NET runs on the server and you cannot run programs on the client computer. The ActiveX object you have shown should work but only in IE and only after the user explicitly authorizes the execution of it. Also the location of notepad.exe might differ depending on the client (could be c:\windows, c:\winnt, ... and some clients running for example on Linux or MacOS don't have such executable)
What you are trying to achieve is not possible because of the nature of application in case of ASP.Net. The application will execute on server and will only send client side HTML to client. Even if your code is syntatically correct, it would open up the utilities on server itself.
This Can be possible by using below code on click of server button or Link.
System.Diagnostics.Process.Start("notepad.exe");
System.Diagnostics.Process.Start("C:\Windows\System32\calc.exe")
Works fine, though you may have to adjust settings on your browser. Be sure calc.exe is in the directory.

Categories