How to read xml file using JS - javascript

I am using the following code to read the xml file from JS
function ReadFile(xmlPath) {
oxmlhttp = null;
try {
// Firefox, Chrome, etc... Browsers
oxmlhttp = new XMLHttpRequest();
oxmlhttp.overrideMimeType("text/xml");
} catch (e) {
try {
// IE Browser
oxmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
return null;
}
}
if (!oxmlhttp) return null;
try {
oxmlhttp.open("GET", xmlPath, false);
oxmlhttp.send(null);
} catch (e) {
return null;
}
var xmlDoc = oxmlhttp.responseXML.documentElement;
alert(xmlDoc);
return oxmlhttp.responseText;
}
It's working fine for IE and Firefox but not in Chrome. the following exception "XMLHttpRequest cannot load the file. Cross origin requests are only supported for HTTP." should occur when i use chrome.
Can anybody know how to read the xml file in chrome using JS?

According to the error, there is some problem with the request domain. You shold alert the domain address of the request:
...
try {
alert(xmlPath) //alerting
oxmlhttp.open("GET", xmlPath, false);
oxmlhttp.send(null);
} catch (e) {
return null;
}
...
and the xmlPath sould not contain and another domain address.
read this issue aboute this: Cross domain Ajax request from within js file

Are you serving the xml file, or are you making tests using your file system ?
If you're using the file system, I'd recommend starting a small HTTP server on your site dir instead.
You can easily start a HTTP server to serve a directory, e.g. serve the current directory with Python:
$ python -m SimpleHTTPServer
Or if you're using Windows, maybe you'll like HFS better for the same purpose: http://www.rejetto.com/hfs/
Cheers!

Related

Accessing text files with Javascript in a chrome app

I would like to be able to edit and save text files in javascript, like the code below, but I have to be able to do it without using system.io, as this is a chrome app. Is there any way to be able to do this?
import System.IO;
var filePath = "data.txt";
function Start() {
if (!File.Exists(filePath)) {
CreateFile();
}
}
function CreateFile() {
var sw: StreamWriter = new StreamWriter(filePath);
sw.WriteLine("Hello World")
sw.Flush();
sw.Close();
print("Done");
}
While you are creating a chrome app, you can use chrome.fileSystem.
This snippet comes from the chrome app samples:
https://github.com/GoogleChrome/chrome-app-samples/tree/master/samples/text-editor
function openFile() {
chrome.fileSystem.chooseEntry(function (entry) {
if (chrome.runtime.lastError) {
showError(chrome.runtime.lastError.message);
return;
}
clearError();
setEntry(entry, false);
replaceDocContentsFromFileEntry();
});
}
For security reasons, JavaScript has no access to local files. It can only access the HTML document. To access external files, such as text files, you must use VBScript. Note that VBScript only works on IE and Edge browsers, and only when they are enabled in the browser's settings.

DOM Exception 11 on XHR request occurring only in Safari

I have a very simple function that downloads chunks of a file using an xhr request that looks like so:
var blobXHR = new XMLHttpRequest();
//api.media.chunkURL() returns the correct URL for each chunk
blobXHR.open("GET", api.media.chunkURL({
fileId: fileID,
chunkId: chunkNumber
}));
blobXHR.responseType = "arraybuffer";
blobXHR.onerror = function (e) {
console.log("Error: ", e);
};
var arrayBuffer;
blobXHR.onload = function (e) {
arrayBuffer = blobXHR.response;
};
blobXHR.send();
Now this download function works without any hitches at all using Chrome, Firefox, and just about every Android browser. Unfortunately, when using anything Safari or iOS based I get a very vague error in blobXHR.onerror(). When I output this error to the console I get this response under "e.currentTarget.responseText":
Error: InvalidStateError: DOM Exception 11
I've looked up many questions similar to this and nothing has seemed to work. Any reason why I would be experiencing this with only Safari/iOS browsers?
Edit: This is what I get when I console.log(blobXHR) within onerror():
This is likely a CORS issue. Make sure your server is properly configured to allow this:
http://enable-cors.org/server.html
Also be mindful that Safari won't allow localhost for CORS.

JavaScript - how to detect if the Custom URL scheme is available or not available?

In Windows operating system i have a custom URI scheme, which is used from
IE, Firefox, Opera, Safari, Google Chrome
to launch Juniper router VPN SSH client (like Cisco). Basically it works as below if the SSH Client is installed, from the web page VPN SSH Client can be launched.
VPN SSH Client
Problem:
sometimes the user did not installed the Juniper router SSH client application from the CD/DVD box, therefore the juniper:open does nothing.
So in that case, i need to detect weather or not the URL scheme is available.
Therefore, I tried Javascript method but its not working exactly. because the juniper:open is actually not web link.
How do i then detect it please?
<script>
// Fails
function test1(){
window.location = 'juniper:open';
setTimeout(function(){
if(confirm('Missing. Download it now?')){
document.location = 'https://www.junper-affiliate.com/setup.zip';
}
}, 25);
//document.location = 'juniper:open';
}
// Fails
function test2(h){
document.location=h;
var time = (new Date()).getTime();
setTimeout(function(){
var now = (new Date()).getTime();
if((now-time)<400) {
if(confirm('Missing. Download it now?')){
document.location = 'https://www.junper-affiliate.com/setup.zip';
} else {
document.location=h;
}
}
}, 300);
}
</script>
Then:
<a onclick="test1()">TEST 1</a>
TEST 2
EDIT
Following suggestions in comments:
function goto(url, fallback) {
var script = document.createElement('script');
script.onload = function() {
document.location = url;
}
script.onerror = function() {
document.location = fallback;
}
script.setAttribute('src', url);
document.getElementsByTagName('head')[0].appendChild(script);
}
and
TEST 2
The price you have to pay, is a duplicated request for the page.
EDIT
This is a good workaround for same-origin policy, which prevents an async version using XMLHTTPRequest to work properly, since SOP restricts cross-domain requests to http and juniper:open would therefore always fail.
function goto(url, fallback) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', url, false);
try {
xmlhttp.send(null); // Send the request now
} catch (e) {
document.location = fallback;
return;
}
// Throw an error if the request was not 200 OK
if (xmlhttp.status === 200) {
document.location = url;
} else {
document.location = fallback;
}
}
EDIT
The initial solution below doesn't actually work 'cause no exception is being thrown if the protocol is not supported.
try {
document.location = 'juniper:open';
} catch (e) {
document.location = 'https://www.junper-affiliate.com/setup.zip';
}
After searching a lot i have not came to anything which can help to solve my problem. But this is what i am now making
1) Write a small tiny webserver which can run in the PC for 24/7 on boot, on crash. Use native python:
python -m SimpleHTTPServer [port]
2) tiny webserver will listen on port abnormal such as 10001 or such TCP ports which never get used
3) from Browser we have to communicate with the http://localhost:10001 just to get a reply
4) based on that reply we have to decide
Otherwise there is no way seems to be available
EDIT: Or you can do this way: InnoSetup - Is there any way to manually create cookie for Internet explorer?

ActiveXObject works when running from .NET but fails after publish

I have an HTML page that has a link to open Microsoft Word on the local machine. The code runs fine while I am running in .NET. Once it is published to a server, ActiveXObject fails without returning any message or Inner Exception.
Has anyone else encountered this before. Since this is running at the client in javascript, I don't understand why it would fail.
function WordCallback(filename) {
var word;
try {
word = new ActiveXObject("Word.Application"); //fails here
}
catch (e) {
$.colorbox.close();
alert('This functionality only works with Internet Explorer.');
return false;
}
try {
//open the document using word
word.Documents.Open(filename);
word.Visible = true; // Make sure Word is visible.
word.Activate();
}
catch (e) {
alert('Unable to open the document.');
}
return false;
}
Its most likely failing because
the client does not have Word installed
the server/site is not trusted
the browser's security does not allow ActiveXObject's to be created
The most likely error is that your server/site is not trusted by the browser. See Allowing ActiveXObject for a trusted site or http://support.microsoft.com/kb/832512

XMLHttpRequest().send() not working in chrome and opera

The following javascript function works fine for IE, Safari and Firefox. But it fails in Chrome(33.0.) and Opera (16.0.1196). Blank HTML page is displayed on loading.
function readTestXMLFile() {
if (window.ActiveXObject) {
var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
xmlDoc.async = 'false';
xmlDoc.load('test.xml');
}
else {
var requ = new XMLHttpRequest();
alert("a");
requ.open("GET", "test.xml", false);
alert("b");
requ.send(null); //This line is not working in chrome and opera
alert("c");
var xmlDoc = requ.responseXML;
alert(xmlDoc);
alert("d");
}
return xmlDoc;
}
Only 'a' and 'b' gets printed. It does not continue after that. Same result is observed if I use requ.send() or requ.send("") instead of requ.send(null).
If I remove the statement requ.send(null), then 'null' value is printed for xmlDoc. Still blank HTML loads.
Please let me know what is the right way to get this work on Chrome and Opera.
Thanks
SRB.
Your error message suggest that you are trying to access a local file which is treated as "Cross origin request" if you try and run local server it should work.
Take a look at this previously asked question with the same problem:
Cross origin requests are only supported for HTTP but it's not cross-domain
Then you would access http://localhost/.../test.xml instead of c:/localhost/.../test.xml
You can also set a flag for Chrome to allow local files to request local files: -allow-file-access-from-files
the call to the XMLHttpRequest.send method is Asynchronous so you need to modify the call a little bit. The modified code below will print the response content when the response is returned successfully:
requ.addEventListener("load", function(e) {
alert(req.responseText);
}, false)
requ.send(null);
Update:
I didn't notice that you made the send request call synchronous.
Edit
You need to launch chrome with this parameter to be able to access local files
--allow-file-access-from-files
ex: c:\Browser\chrome.exe --allow-file-access-from-files
I think that the problem is that you're passing null to the send() method. You are making a GET request, so you should call send without parameters. I think chrome throws an exception because of that. Just remove the null

Categories