I have a problem loading an external page into my div using Javascript. I get a NS_ERROR_FAILURE in the console.
var req = new XMLHttpRequest();
req.open("GET", 'helpInfo.html', false);
req.send(null);
var page = req.responseText;
document.getElementById("helpInfo").innerHTML = page;
If you want to use javascript you can build a Node.js server and route all your calls through that. That will help the XSS problem.
Related
On a website I am automating with the help of Cefsharp I have the need to provide a javascript File.File(). The file I want to give it is locally saved and could be anything from pdfs to office documents or images. As far as CefSharp is concerned I have implemented a ISchemeHandlerFactory and ResourceHandler adding a test:// scheme and for example I have successfully added a JS file like this.
var head = document.head;
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'test://local/folder/mytest.js';
head.appendChild(script);
According to the API to create a file I need
bits - An Array of ArrayBuffer, ArrayBufferView, Blob, or DOMString objects — or a mix of any such objects. This is the file content encoded as UTF-8.
So I have my scheme of test:// to give me a local file what do I need to use in javascript to get this into a file?
I worked it. I first tried a fetch but that would not let me use a custom scheme. So I had to use XMLHttpRequest
(function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var contentType = xhttp.getResponseHeader("Content-Type");
var file = new File([this.response],'3Markets.xlsx', {type: contentType,});
//use my new file etc
}
};
xhttp.open('GET', 'test://local/folder/3Markets.xlsx', true);
xhttp.responseType = "arraybuffer";
xhttp.send();
})()
The only issue or worry i have is I currently have to call
CefCommandLineArgs.Add("disable-web-security", "disable-web-security")
which i will have to have a look around how I can achieve this without disabling web security or eventually ask a question here.
I need a way to insert the text downloaded from a .txt file from a URL into an element or variable which i can use further.
I have tried adding the URL to an object element which displays the text correctly, but I do not know how to add this text into a variable.
var storage = firebase.storage();
var storageRef = storage.ref();
var tangRef = storageRef.child('Recs');
var fileRef = tangRef.child("rec3.txt");
fileRef.getDownloadURL().then(function(url)
{
alert(url);
var para = document.getElementById('p1');
var par = document.createElement("object");
par.setAttribute('data', url);
para.appendChild(par);
}).catch(function(error)
{
console.error(error);
});
As mentionned, you can get some file through an object HTML element as you can do through a script HTML element to load a file. From these elements you won't have a same-origin policy problem, that's why your document is loaded with setAttribute and appendChild.
If you tried to access a resource by XHR or if you tried to interact with a document (both by JS), which are not from the same origin than your current resource, you will need to manage a same-origin policy mechanism see : https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy
You can choose XHR or choose to access the nested document from the object HTML element, in both case you will have the same-origin policy problem. This is for security reasons which are linked with JavaScript.
If you choose nested document you could do something like this :
<div id="p1"></div>
<script>
var url = "https://firebasestorage.googleapis.com/v0/b/ninjatest-1b0ab.appspot.com/o/random%20text%20file.txt?alt=media&token=c09ae3ee-6a01-4f2b-b2b3-2f57ed7ff111";
// or
// var url = "http://localhost:4000/file.txt";
var para = document.getElementById('p1');
var par = document.createElement("object");
par.setAttribute('data', url);
para.appendChild(par);
par.onload = function() {
var doc = par.contentDocument || par.contentWindow.document;
var data = doc.body.childNodes[0].innerHTML;
console.log(data);
};
</script>
If you run this code, you can see that it doesn't accept cross-origin. This is because i'm trying to get a document (nested in the HTML document) which is from another domain. The browser won't let me access it. In the other hand, if i run in local with a node server, it allows me to get it without the error.
If you choose to use XHR (XMLHttpRequest) you can do something like that :
var data;
var url = "https://firebasestorage.googleapis.com/v0/b/ninjatest-1b0ab.appspot.com/o/random%20text%20file.txt?alt=media&token=c09ae3ee-6a01-4f2b-b2b3-2f57ed7ff111";
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
data = xhr.responseText;
console.log(data);
}
};
xhr.open('GET', url);
xhr.send();
Again here, it won't work because of the different origin. In the two situations, it's the browser which implements a security rule. You can fix it if you have access to the server part. On the server, you could tell the browser (by HTTP header) to allows client from different origin.
With XHR you need to search about CORS.
With Nested document, you can look here :
SecurityError: Blocked a frame with origin from accessing a cross-origin frame
How Can I Bypass the X-Frame-Options: SAMEORIGIN HTTP Header?
If you don't have access to the server part, you could grab the file with a GET request from a server that you own (and so have access to the server part). In this case, you won't have the browser security issue because from your server, you will serve the file without the restriction of same-origin. It will be a proxy server solution.
With Firebase
When you create project with Firebase you can configurate the server part to allow the XHR as mention here : https://firebase.google.com/docs/storage/web/download-files#download_data_via_url
Firstly install Google Cloud SDK to have gsutil : https://cloud.google.com/storage/docs/gsutil_install#install
Then create a .json file on your computer : https://cloud.google.com/storage/docs/configuring-cors#configure-cors-bucket
Then execute this command : gsutil cors set cors.json gs://<your-cloud-storage-bucket>
JSON file example :
[
{
"origin": ["*"],
"method": ["GET"],
"maxAgeSeconds": 3600
}
]
I created a Firebase account, tried it and it works very well.
Working example with XHR (you can run it) :
var data;
var url = "https://firebasestorage.googleapis.com/v0/b/first-app-a7872.appspot.com/o/firebase.txt?alt=media&token=925fef9e-750e-40e5-aa92-bdfe8204d32e";
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
data = xhr.responseText;
console.log(data);
}
};
xhr.open('GET', url);
xhr.send();
https://codepen.io/anon/pen/JmoqQY?editors=1010
In HTML file:
<div id="p1">
</div>
script
url = "https://firebasestorage.googleapis.com/v0/b/ninjatest-1b0ab.appspot.com/o/random%20text%20file.txt?alt=media&token=c09ae3ee-6a01-4f2b-b2b3-2f57ed7ff111"
var para = document.getElementById('p1');
var par = document.createElement("object");
par.setAttribute('data', url);
para.appendChild(par);
EDIT: I made a stackblitz to try to see if I could extract the data in the text file into a variable for manipulation.
https://stackblitz.com/edit/angular-eyhaj5
I was unable to find a way. Problem is that because of CORS policy in browsers you are not supposed to open files outside of your own site.
To get around this you have to either have to send the URL to a function on your server that downloads the textFile and then makes it accessible in a folder.
Or you could set up a proxy server that allows cors. Or you could ask the owner of the text file to make it into an API.
Possibly it was a bad idea to put the textfile in firestorage in the first place. If you are the owner of the text file, it would maybe be better to put the text in a firestore database rather than save it as a textfile.
Hello I'm new at web developing so I apologize if my methods/questions makes no sense.
I am trying to load an audio file from a server directory to an audio html element. I was following fetch data example in this tutorial
var xhr = new XMLHttpRequest();
xhr.open('GET', http://*ipAddress*/audioUpload/test.mp3, true, *serverUsername*, *serverPassword*);
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status == 200) {
var blob = new Blob([this.response], {type: 'mp3'});
var audioReader = new FileReader();
audioReader.onload = function(d) {
var e = document.createElement("audio");
e.src = d.target.result;
e.id = "audioHTMLId";
e.setAttribute("type", 'mp3');
e.setAttribute("controls", "controls");
e.setAttribute("autoplay", "true");
document.getElementById("container").appendChild(e);
}
audioReader.readAsDataURL(blob);
}
};
xhr.send();
}
However I am getting this statement in console log:
GET http://*ipAddress*/audioUpload/test.mp3 net::ERR_CONNECTION_REFUSED
And don't know why.
Also I was wondering if there were a better way to play/get audio files on client's audio html element for large mp3 files (1-1.5 hour long)?
Is this by chance in Chrome? I've send this when you try and send a request and the server disconnects. This can be HTTPS / SSL related, or a problem with the actual server . I'd check whether or not you can actually hit the file like so:
wget http://*ipAddress*/audioUpload/test.mp3
It could be that said server is actually unreachable from wherever your environment is.
As for the second half of your question, you might just want to upload the audio to youtube and embed it, rather than dealing with the hassle of dealing with it yourself (storage, bandwidth, etc). However, I'm sure someone more versed than I could give you a better answer on that.
You need to set the authorization headers manually:
....
xhr.open('GET', http://*ipAddress*/audioUpload/test.mp3, true);
xhr.setRequestHeader("Authorization", "Basic " + btoa(*serverUsername* + ":" + *serverPassword*))
....
Is there a method in javascript to load a page without actually show that page?
I want to load a php page which will handle the database insertion tasks.
Use AJAX to get/send data to the serverside?
Yes there is, you can use the XMLHttpRequest for this.
here is a example
function done() {
console.log(this.responseText); // The response from the server
};
var XHR = new XMLHttpRequest();
XHR.onload = done; // Set the onload function
XHR.open("get", "something.php", true); // Type & File
XHR.send(); // Send the request
Here is some documentation on that MDN XMLHttpRequest
Using XMLHttpRequest, I can retrieve a page / file dynamically:
var request = new XMLHttpRequest();
request.onload = function() {
console.log(this.responseText);
};
request.open("get", "/my_file.txt", true);
request.send();
However, the onload callback only runs when the entire page is downloaded. There are no methods to return the page bit by bit while it is being loaded. This means that XMLHttpRequest does not have access to a huge file until it is loaded entirely.
Is JavaScript able to retrieve the content of files (sent through HTTP 1.0) while they are being loaded dynamically?