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/
Related
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
We are currently using log4javascript-popUpAppender console for development and would like to store the details to local file.
Though we can use the AjaxAppender to send log messages to the server and log those messages to log4j set up with a rolling file appender, we are looking for a way to use something similar to FileAppender in Log4js.
Any idea/suggestion?
This is similar to http://www.techques.com/question/1-3626960/JavaScript-logger-into-a-rolling-file
Since we have already implemented log4javascript, we would like to stick with the same framework.
This is still not really viable in browsers, in my view. I've had another look at it; these are my observations:
In Firefox, I don't think it is currently possible to write to the local file system at all, even if the user approves. From Firefox 17 (I think), privileged code can no longer run in a web page, which rules out the old method floating around on the web (e.g. here)
IE still has its ActiveX method of doing this, but it's more locked-down than ever and requires various actions by the user to enable it.
HTML5 has a file system API which is currently only implemented by new versions of Chrome and Opera. It writes files to a carefully sandboxed location and offers no control over actual file name or path.
Safari currently has no way to do this, as far as I can tell.
In general, browsers sensibly offer little or no access to files on the local file system, so it's an unreliable way to log. However, I've written a rough BrowserFileAppender that implements the HTML5 and ActiveX methods which you're welcome to use if you find it helpful:
https://gist.github.com/timdown/6572000
Adding FileAppender solution for IE and Firefox.
function FileAppender() {}
FileAppender.prototype = new log4javascript.Appender();
FileAppender.prototype.layout = new log4javascript.SimpleLayout();
FileAppender.prototype.append = function(loggingEvent) {
var appender = this;
var getFormattedMessage = function() {
var layout = appender.getLayout();
var formattedMessage = layout.format(loggingEvent);
if (layout.ignoresThrowable()) {
formattedMessage += loggingEvent.getThrowableStrRep();
}
return formattedMessage;
};
writefile = function(destinationFile, message) {
if (isEmpty(destinationFile)) {
log.error("Source location unknown");
return;
}
if ($.browser.msie) {
try {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var file = fso.OpenTextFile(destinationFile, 8, true);
file.WriteLine(message);
file.close();
} catch (e) {
log.error("Please validate if file exist");
}
} else {
netscape.security.PrivilegeManager
.enablePrivilege("UniversalXPConnect");
this.fso.initWithPath(destinationFile);
if (!this.fso.exists()) {
// create file if needed
this.fso.create(0x00, 0600);
}
var file = Components.classes["#mozilla.org/network/file-output-stream;1"].createInstance(Components.interfaces.nsIFileOutputStream);
file.init(this.fso, 0x04 | 0x08 | 0x10, 064, 0);
var line = message;
file.write(line, line.length); // write data
file.close();
}
};
getFile = function() {
return "c://temp//log//Javascriptlog.log";
};
writefile(getFile(), getFormattedMessage());
};
FileAppender.prototype.toString = function() {
return "FileAppender";
};
log4javascript.FileAppender = FileAppender;
I have the following code:
xmlDoc=loadXMLDoc("dbbackup.xml");
x=xmlDoc.getElementsByTagName("record");
alert(x);
for (i=0;i<3;i++) {
newel=xmlDoc.createElement("edition");
newtext=xmlDoc.createTextNode("first");
alert("x : "+x[i]);
alert("newtext :"+newtext.nodevalue);
x[i].appendChild(newel);
alert("sd");
}
function loadXMLDoc(dname) {
if (window.XMLHttpRequest) {
xhttp=new XMLHttpRequest();
} else {
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",dname,false);
xhttp.send();
return xhttp.responseXML;
}
I have created dbbackup.xml in the same location and the XML file looks like:
<sticky>
<record></record>
</sticky>
But after running my script the xml file is not getting updated.
Javascript cannot modify files on disk, it only runs for the client in the client's web browser.
To actually write to and from files on a server, you have to use server-side languages and technologies, like PHP or ASP.
I made this - making XML at client side then using everyday praksis
Mike
function makeSlot() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) showBon(); }
xmlhttp.open("POST","crMakeSlot.php",true);
xmlhttp.send(wrapUp());
}
/***
* make the final transaction - using XML
*/
function wrapUp () {
var transaction = document.implementation.createDocument("","", null);
var operator = document.createElement("operator");
var textblok1 = document.createTextNode(document.getElementById("rText").value);
operator.appendChild(textblok1);
var root = document.createElement("transaction");
root.setAttribute("tstamp", now);
root.setAttribute("sequenceno", zSequenceNo.textContent);
if (parseInt(document.getElementById("zDankort").value) > 0) root.setAttribute("dankort", document.getElementById("zDankort").value);
if (parseInt(document.getElementById("zCash").value) > 0) root.setAttribute("cash", document.getElementById("zCash").value);
if (parseInt(document.getElementById("zCredit").value) > 0) root.setAttribute("credit", document.getElementById("zCredit").value);
if (parseInt(document.getElementById("zCheck").value) > 0) root.setAttribute("check", document.getElementById("zCheck").value);
if (parseInt(document.getElementById("zGiftcard").value) > 0) root.setAttribute("giftcard", document.getElementById("zGiftcard").value);
if (parseInt(document.getElementById("zVoucher").value) > 0) root.setAttribute("voucher", document.getElementById("zVoucher").value);
root.appendChild(operator);
var divObj = document.getElementsByTagName("div");
/***
* when column value is 4, then we have our data complete - next cycle
*/
for (ix = 0; ix < divObj.length; ix++) {
switch (divObj[ix].getAttribute("column")) {
case "1": var row = document.createElement("row"); row.setAttribute("item",divObj[ix].textContent);
case "2": row.setAttribute("price",divObj[ix].textContent);
case "3": row.setAttribute("quantum",divObj[ix].textContent);
case "4": root.appendChild(row);
default: break;
}
}
transaction.appendChild(root);
return(transaction);
}
SomeKidWithHTML is right.
JavaScript is designed to only modify a file, in memory, that is loaded inside a browser framework.
Think of the browser as a sandbox that your kids (html, xml, etc.) can play in. As long as Johnny (xml) is in the sandbox playing, all is well. But if Johnny were allowed to play outside of that sandbox, just think of the havoc that could be done on your machine by websites.
There is NO WAY a JavaScript can permanentally affect a file on your local machine, by itself. It can only play inside the sandbox (locally, it can make calls to Java, or an other API, to affect change, but that's a whole other deal).
JavaScript is client side only. If you expect it to affect a server, it can only do it through calls back to the server. At the server you will need some kind of programming (asp.net, java, php, html, others) to receive and answer that call and do something with it.
JavaScript, by itself, is very powerful... but only inisde the sandbox (browser). For it to affect anything else outside of that browser it must depend on other programs already in place and ready to receive those requests.
And this is all in the name of security, mostly.
You can collect data from the web page in client side and send them to the server (ajax), which will then generate the xml file and send back a link to the file (ajax). Use javascript to generate a download link using the link returned by the server.
This is the way I do to solve the problem in one of my project.
I'm using the following code to read a local text file from a local Javascript file, but it isn't working:
var txtFile = new XMLHttpRequest();
txtFile.open('GET', fileLocation, true);
The error I get:
XMLHttpRequest cannot load file:///C:/File.txt. Cross origin requests are only supported for HTTP.
Any ideas?
You can not access local resources from javascript,
You should put this file in your site and try to access it via fileLocation like http://mywebsite/File.txt
look at this:
var fileContent='';
var theLocation='';
function readFileViaApplet(n) {
document.f1.t1.value='Reading in progress...';
document.ReadURL.readFile(theLocation);
setTimeout("showFileContent()",100);
}
function showFileContent() {
if (document.ReadURL.finished==0) {
setTimeout("showFileContent()",100);
return;
}
fileContent=document.ReadURL.fileContent;
document.form1.textarea1.value=fileContent;
}
I'm transforming an XML document with XSLT in Internet Explorer 7. My XSLT imports/includes -- I've tried both -- another XSLT with the following line:
<xsl:import href="utils.xsl" />
This results in an HTTP request for the included file every time the including XSLT is used, even if a reference to the parent XSLT is cached and re-used. IE sends a Pragma: no-cache header on each request for the import/include request.
Is it possible to prevent these repeated HTTP requests?
Can I get IE to cache the file in the client?
If not, can I get IE to send an "If-Modified-Since" header?
For completeness, here's the corresponding transformation JavaScript:
var XMLUtil = {
// transforms the sourceStr using the given xslDoc
transformString: function(sourceStr, xslDoc /*XMLDOM doc*/) {
var sourceDoc = XMLUtil.loadFromString(sourceStr);
var resultDoc = new ActiveXObject("Microsoft.XMLDOM");
sourceDoc.transformNodeToObject(xslDoc, resultDoc);
return resultDoc;
},
// creates an XMLDOM document from a string containing XML
loadFromString: function(xml) {
var doc = new ActiveXObject("Microsoft.XMLDOM");
doc.async = false;
doc.loadXML(xml);
if (doc.parseError.errorCode != 0)
throw "Error parsing XML: " + doc.parseError.errorCode;
return doc;
}
}
The responses to a similar question recommends setting ForcedResync to false.
But Qi Samuel Zhang's response cautions
ForcedResync should work for most
cases, but the ForcedResync in MSXML3
has known issues to mitigate backward
compatibility, please use
MSXML2.DOMDocument.6.0 when possible.