How do I read a JSON file using HTML? - javascript

Here is my code:
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script>
$(function() {
var thing = [];
var bar = $.getJSON('C:\Users\cccompro\foo.json', function(obj) {
for (i = 0; i < obj.length; i++) {
thing.push(obj[i]);
}
});
});
</script>
I'm not sure why it doesn't work. "foo.json" contains an array of objects.

If you are trying the code at Question at Chrome or Chromium browsers, launch the browser instance with --allow-file-access-from-files flag set. Note that open instances of Chrome or Chromium should be closed when you launch the browser or the instance will be launched with the open browser instances' configuration folder, instead of with the flag set. You can launch Chrome or Chromium with an existing instance open and honoring the flag by using --user-data-dir flag with value set a different directory than open instance of Chrome or Chromium.
Technically, it is also possible to write to user file system without using an extension with window.webkitRequestFileSystem. Though using chrome.fileSystem within an extension provides an API designed to achieve the read/write.
See
Jquery load() only working in firefox?
Read local XML with JS
How to Write in file (user directory) using JavaScript?
How to use webkitRequestFileSystem at file: protocol
JavaScript/Ajax Write to File
Using <input type="file"> element
How to print all the txt files inside a folder using java script

You cannot read files directly from the users hard drive without the browsers permission. This would be a huge security issue if you could even though there are ways to allow this (checkout guests answer).
You could however try to make the user select the file and then read it with Javascript.
This is called the HTML 5 file API.
However, this doesn't work for any browser and you probably have to use a server anyway in this case.
For more information on this checkout this or this post.

Related

I can't use the browser object from the settings page of my Firefox add-on

I'm making a Firefox Add-On that needs to keep track of a list of words. From the main javascript file I can read and modify a stored Array under the name "list", but when I try to access it from the settings page I get an error:
ReferenceError: browser is not defined
Here is the function from which I try to access the local storage (this is in the .js file that is used in my .html settings page).
function EmptyList() {
if (confirm("Empty list?")){
browser.storage.local.set({
list : []
});
}
}
I don't understand what am I doing wrong. I'm not doing anything different from what they do in the mozilla tutorial.
Apparently it has something to do with the cache.
Disable and reenable the add-on (or remove it and add it again) and it works. Go figure.

Replacing XML DataIsland Files in asp.net

The app I am working on, currently uses XML dataisland files to retrieve the dropdown data. Below is the code that defines the file.
<xml id="DefaultDataIslands" src="../XMLData/DataIslands-<%=((User.Identity).Database)%>.xml">
</xml>
Below is an example code that uses these XML dataislands.
var oDataIsland = document.getElementById("DefaultDataIslands");
var oXmlNodes = oDataIsland.XMLDocument.selectNodes("XMLDataIslands/DataIsland[#ID='DIMRGroup']/Option");
This oDataIsland line is used about 4k times total in the application. The application itself is intranet, so, I can even ask the users to download the xml files directly. Whole point is to keep the changes required to minimum, while removing all traces of XML tags. I want to make sure that application works on Chrome once this thing is completed.
I checked the link from mozilla regarding the dataislands here. https://developer.mozilla.org/en/docs/Using_XML_Data_Islands_in_Mozilla
Below is the code based on that mozilla link.
var doc = document.getElementById(strDataSource).contentDocument;
var mainNode = doc.getElementsByTagName("DataIsland");
var oXmlNodes;
var strOptions = "";
//finds the selected node based on the id, and gets the options for that id
for (i = 0; i < mainNode.length; i++) {
if (mainNode[i].getAttributeNode("ID").nodeValue == strDataMember) {
oXmlNodes = mainNode[i].getElementsByTagName("Option");
}
}
This code reads the data properly, works perfectly in IE (10 with standards mode, no quirks), was easy enough change to do in the full solution.
Only problem is, document.getElementById(strDataSource).contentDocument; line fails in Chrome. This is the same line as what was mentioned in Mozilla's documentation. But somehow contentDocument property is undefined on chrome.
So, I need some other suggestion on how to get this fixed. I tried other methods, using HTTPRequest (too many request per page), using JSON (requires changing existing methods completely), using backend to process XML instead of doing it client side (requires architectural changes). Till now, all these ideas failed.
Is there any other method that I can use? Or should I fix the contentDocument issue?
To allow contentDocument in Chrome, you will have to use --allow-file-access-from-files. Following are the steps for doing so:
Get the url of your Chrome Installation path to your chrome
installation e.g
C:\Users-your-user-name\AppData\Local\Google\Chrome\Application>
Launch the Google Chrome browser from the command line window with
the additional argument ‘–allow-file-access-from-files’. E.g ‘path
to your chrome installation\chrome.exe
--allow-file-access-from-files’
Temporary method you can use each time you are testing
Copy the existing chrome launcher
Do as above and save it with a new name e.g chrome - testing
Alternatively, you can simply create a new launcher with the above and use it to start chrome.
Source

Check if Opera extension installed in developer mode

Is there some predicate or variable that one can use in the extension code to determine whether it was installed normally or in developer mode?
(I'd like to put some debug output visible only in developer mode.)
No, there is no way to get this info directly.
But what you can do is the following:
Create a file with the name debug.txt (or what you want) in your extensions folder.
Make sure you always delete this file when creating the zipped .oex-file!
Now you can add the following code to your background script:
var debugFile = opera.extension.getFile("/debug.txt");
if (debugFile) {
//This is debug mode!!
}
You will get a valid [File]-Object if the file exists and null otherwise.
(Infos: http://dev.opera.com/articles/view/extensions-api-resourceloader/)

JS Bookmarklet to open PDF-Files in External Viewer?

I have a program (Mendeley) that tries to open PDF files that are stored locally by accessing the URL: http://path.to/file.pdf (instead of file://path.to/file.pdf). This results in an error in my browser (not unexpected).
What I would like to do is have a javascript bookmarklet that uses the URL in the address bar (which is basically correct besides the http part) and opens the file in an external viewer (Acrobat in my case). My latest creation (inspired by other examples on SO has been):
javascript:var a = (location.pathname);
var b = ('file://schbs02'+a);
window.location = (b);`
This does NOT work; in Chrome (latest version) nothing happens. Is it an inherent limitation of bookmarklets (for security purposes) that they can not open local files or is there something wrong with the code?

How to bypass document.domain limitations when opening local files?

I have a set of HTML files using JavaScript to generate navigation tools, indexing, TOC, etc. These files are only meant to be opened locally (e.g., file://) and not served on a web server. Since Firefox 3.x, we run into the following error when clicking a nav button that would generate a new frame for the TOC:
Error: Permission denied for <file://> to get property Location.href from <file://>.
I understand that this is due to security measures within FF 3.x that were not in 2.x, in that the document.domain does not match, so it's assuming this is cross-site scripting and is denying access.
Is there a way to get around this issue? Perhaps just a switch to turn off/on within Firefox? A bit of JavaScript code to get around it?
In firefox:
In address bar, type about:config,
then type network.automatic-ntlm-auth.trusted-uris in search bar
Enter comma separated list of
servers (i.e.,
intranet,home,company)
Another way is editing the users.js.
In users.js, write:
user_pref("capability.policy.policynames", "localfilelinks");
user_pref("capability.policy.localfilelinks.sites", "http://site1.com http://site2.com");
user_pref("capability.policy.localfilelinks.checkloaduri.enabled", "allAccess");
But if you want to stop all verification, just Write the following line into users.js file:
user_pref("capability.policy.default.checkloaduri.enabled", "allAccess");
You may use this in firefox to read the file.
function readFile(arq) {
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
var file = Components.classes["#mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
file.initWithPath(arq);
// open an input stream from file
var istream = Components.classes["#mozilla.org/network/file-input-stream;1"].createInstance(Components.interfaces.nsIFileInputStream);
istream.init(file, 0x01, 0444, 0);
istream.QueryInterface(Components.interfaces.nsILineInputStream);
var line = {}, lines = [], hasmore;
do {
hasmore = istream.readLine(line);
lines.push(line.value);
} while(hasmore);
istream.close();
return lines;
}
Cleiton's method will work for yourself, or for any users who you expect will go through this manual process (not likely unless this is a tool for you and your coworkers or something).
I'd hope that this type of thing would not be possible, because if it is, that means that any site out there could start opening up documents on my machine and reading their contents.
You can have all files that you want to access in subfolders relative to the page that is doing the request.
You can also use JSONP to load files from anywhere.
Add "file://" to network.automatic-ntlm-auth.trusted-uris in about:config

Categories

Resources