Load local XML file with IE 11 - javascript

I am working on a simple project which involves loading local .xml file into DOM structure by local .html file. We can assume that .html and .xml file are placed in the same folder on the same computer. Problem is that IE 11 disallows any interaction with local xml file. (SCRIPT5: Access is denied.)
So far i tried this solutions (Solution 1,2 are tested and functional within Mozilla FireFox and Google Chrome, Microsoft Edge has some different problem - see first code snippet):
Synchronous/Asynchronous XMLHttpRequest (async in example)
function loadXMLDoc(doc)
{
try{
xmlhttp = new XMLHttpRequest();
}catch(e){
try {
xmlhttp = new ActiveXObject("MSXML2.XMLHTTP.3.0");
}
catch(e){
try {
xmlhttp = new ActiveXObject("MSXML2.XMLHTTP");
}
catch(e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e) {
alert("XMLHTTP Not Supported On Your Browser");
}
}
}
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200) /*Microsoft edge returns status 0 here */
{
alert(xmlhttp.responseText);
}
};
xmlhttp.open("GET",doc,true);/*IE11 prints "SCRIPT5: Access is denied." into console*/
xmlhttp.send();
}
And JQuery async solution
window.onload = function() {
$.ajax({
url: "output.xml",
aync: true,
success: myHandle,
isLocal:true,
dataType: "xml"
});
}
function myHandle(data) {
alert(data);
}
Third solution consists of simple node.js webserver (see Using node.js as a simple web server)
but this seems to be a too large gun for me.
Also there is a problem that web server has to be start explicitly via cmd / script, but i just want to hit .html and see interpreted xml data.
TL;DR My questions are:
Is there any workaround that makes local .xml files accessible for
IE11?
Why is this "security risk" for IE but not for others?
Note:
Since .xml file can have more Mb, async solutions are prefered for me.
Thank you.

If you're trying to provide the file path as a local path, then it won't work in other browsers as well, using plain javascript, and you may get Cross domain errors. If you have a web server, you can put the file there in the appropriate location, and provide the path as "http://localhost/.../file.xml". This may help.

Well, what I propose as a backup opportunity is to go away a bit from the html + js solution and try XML + XSLT. This should not have any security issues, the only thing that changes for you - you don't need to open index.html but you'll need to open output.xml in your browser.
Also, you would need to add to your XML file the pointer to your XSLT file, see e.g. here how to do that.
Once you loaded your XML and processed it with XSLT you have the same HTML with the same JavaScript, but all data is already rendered. XSLT is quite powerful and I am sure it will fulfill all your requirements

Related

How to read text file from filesystem in JavaScript

I have tried different approaches to read a text file from the local file system in JavaScript and display the content of the file in alert() but all to no avail.
Approach 1
function readTextFile(file) {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file , false);
rawFile.onreadystatechange = function () {
if (rawFile.readyState === 4) {
if (rawFile.status === 200 || rawFile.status == 0) {
var allText = rawFile.response;
document.getElementById("content").innerText = allText;
alert(allText);
}
} else {
alert("Can't read the file");
}
}
rawFile.send(null);
}
readTextFile("FormulaQuestion.txt");
The FormulaQuestion.txt file is in the same directory with the html file, this approach shows an empty alert window on the browser
Approach 2 using fetch method
fetch('FormulaQuestion.txt')
.then(response => response.text())
.then((data) => {
alert(data);
})
This doesn't show anything
Approach 3 using JQuery
$.get('FormulaQuestion.txt', function (data) {
alert(data)
}, 'text');
This doesn't work either.
I am building a desktop application that uses a web browser control to load html file which is embedded into the application. The application reads the string from sqlite database and save it in the FormulaQuestion.txt file, then refreshes the WebControl component which reloads the html file.
Now when the html file is reloaded, the JavaScript should read the text file and display it on alert() which once the alert is able to display the file content, i will then set it to a paragraph and remove the alert().
Please someone should help me out.
Browsers by design do not allow access to the file system for JavaScript, as allowing such access would be a serious security concern.
To provide the FormulaQuestion.txt file to your script you will need to host the file on a server and request it via a HTTP request (like with your fetch). The key thing here is that a server is needed to actually transmit the file over the HTTP protocol to your script.
If working locally, there are many options for running a local server.
The npm serve module,
Wamp
Apache
You may also want to try out some free tier services like Vercel or Netlify. Both I believe allow you to just drag/drop a file and it will host it for you.

Load local xml file using javascript in Google Chrome

I think until v5 of Google Chrome the below code worked. Now in the latest version I get the following error when opening my webpage locally:
"XMLHttpRequest cannot load file:///C:/Temp/Course.xml. Cross origin requests are only supported for HTTP."
The Javascript code:
function getXmlDocument(sFile) {
var xmlHttp, oXML;
// try to use the native XML parser
try {
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", sFile, false); // Use syncronous communication
xmlHttp.send(null);
oXML = xmlHttp.responseXML;
} catch(e) {
// can't use the native parser, use the ActiveX instead
xmlHttp = getXMLObject();
xmlHttp.async = false; // Use syncronous communication
xmlHttp.resolveExternals = false;
xmlHttp.load(sFile);
oXML = xmlHttp;
}
// return the XML document object
return oXML;
}
// get the best ActiveX object that can read XML
function getXMLObject() {
// create an array with the XML ActiveX versions
var aVersions = new Array("Msxml2.DOMDocument.6.0", "Msxml2.DOMDocument.3.0");
// loop through the array until we can create an activeX control
for (var i=0; i<aVersions.length; i++) {
// return when we can create the activeX control
try {
var oXML = new ActiveXObject(aVersions[i]);
return oXML;
}
catch(e) {
}
}
// could not create an activeX, return a null
return null;
}
I really don't want to be forced to open the web page from a web server every time.
Local file access is disabled by default for security reasons. Try starting Google Chrome from the command line with the argument --allow-file-access
It would be more secure if you just start a local webserver and fetch your html and xml from localhost.
You can easily avoid deploying of the files by just let the server serve the contents of a local folder in which you place your xml.
This way you avoid
having to start chrome in an unsecure mode
having problems when you later deploy your app to a server on the internet
server to go is an example for an easy to install webserver http://www.server2go-web.de/

How to load local JSON files in Javascript

I'm writing a web app (well, actually it will eventually be an OS X Dashboard widget, but I decided to prototype it first as a simple web page) that needs to load some initializing data from a local JSON file. My code looks like this:
function loadDatos() {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'datos.json', true);
xobj.onReadyStateChange = function () {
if (xobj.readyState == 4) {
var jsonTexto = xobj.responseText;
ProcessTheData(jsonTexto);
}
}
xobj.send(null);
}
The function get called from an onLoad() event in the HTML file's BODY tag. Now, from what I see when debugging, the function gets executed, but the onReadytStateChange event handler never gets called.
What should I do? I thought it was a bit odd to use a XMLHttpRequest to access a local file, but the new tutorials I've seen that deal with this issue seem to say that it should work (the 99% of docs I've seen talk about how to load JSON from a remote server, not from a local file).
I'm testing using Firefox 3.6.10, but I've also tried with Safari 4.
onreadystatechange property has no capital letters. See: MDC XMLHttpRequest
Unless we add extension .json and MIMETYPE application\json, IIS will throw an error.
See here: http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/cd72c0dc-c5b8-42e4-96c2-b3c656f99ead.mspx?mfr=true

How can I access the plain text loaded in an <iframe> on IE?

I have an <iframe> whose src points to a plain text file (not HTML). The text gets loaded and displayed on screen, but seems to be hidden to JavaScript.
In other browsers, iframe.contentWindow.document.body.innerText is enough to get it for you, but IE returns an empty string in that case.
Is there a way that IE can access the text inside the file without involving a server?
You can read this file using XmlHttpRequest. If the browser can read it, so can XmlHttpRequest.
/* Read a file using xmlhttprequest
If the HTML file with your javascript app has been saved to disk,
this is an easy way to read in a data file. Writing out is
more complicated and requires either an ActiveX object (IE)
or XPCOM (Mozilla).
fname - relative path to the file
callback - function to call with file text
*/
function readFileHttp(fname, callback) {
xmlhttp = getXmlHttp();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4) {
callback(xmlhttp.responseText);
}
}
xmlhttp.open("GET", fname, true);
xmlhttp.send(null);
}
/*
Return a cross-browser xmlhttp request object
*/
function getXmlHttp() {
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else if (window.ActiveXObject) {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp == null) {
alert("Your browser does not support XMLHTTP.");
}
return xmlhttp;
}
Call the readFileHttp(fname, callback) using the iframe.src property for the fname parameter.
The callback parameter should be a function that does whatever you want with the result.
Something like this:
var myIFrame = document.getElementById('iframeIdGoesHere');
readFileHttp(myIFrame.src, function(result){
//process the result
});
EDIT based on comment and edit in question:
It might be that body is not available as a js property on the document. You could try:
iframe.contentWindow.document.getElementsByTagName('body')[0].innerText
My original answer (kept only as reference because of the comment):
You
say in a comment that you pull the
path from an <input type='file' />.
You can use that to upload the file to
the server, and then read it using
simple file reading mechanisms. (after
all, the <input type='file' /> is
meant for server uploads...)
Just a shot in the dark, but have you tried the innerHTML property?
Alternatively, the more "proper" way to do this is to request the file directly with XMLHttpRequest.
and
window.frames[0].document.getElementsByTagName("body")[0].innerHTML
?

javascript source path problem

i have a problem to access some file from different source.
for example i have html folder and xml folder in same directory.
then from html file i wanna access xml file in xml folder.
in html i have script to call file
xmlDoc=loadXMLDoc("../xml/note.xml");
why this path doesnt work as well?
this is my code of loadXmlDoc()
function loadXMLDoc(dname)
{
var xmlDoc;
if (window.XMLHttpRequest)
{
xmlDoc=new window.XMLHttpRequest();
xmlDoc.open("GET",dname,false);
xmlDoc.send("");
return xmlDoc.responseXML;
} // IE 5 and IE 6
else if (ActiveXObject("Microsoft.XMLDOM"))
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.load(dname);
return xmlDoc;
}
alert("Error loading document");
return null;
}
I would suggest using root relative, loadXmlDoc('/xml/note.xml') as this will always start at the same point ( the root ) and you don't have to keep ascending up with ../../.
The path is relative to the current page location (the current page you're browsing).
I suggest using the full http:// url, such as loadXMLDoc("http://example.com/xml/note.xml") or loadXMLDoc("/xml/note.xml").
You'll need to better describe what you mean by "doesn't work". However, judging from your code I'm guessing you are trying to get an XMLDOM object back from an XML source. Whenever I have trouble with XML sources I find the following list helps me track down my problem
Have you checked these things?
Did you set your content type to text/xml?
Is your request actually making it to the server and back?
When you alert/examine the responseText, do you see anything that does not belong?
Is your XML properly formatted? Run it through a validator.
With more information about what is failing I'll be better able to help.
Best of luck!
Cheers.

Categories

Resources