user4441304
user4441304

Reputation:

Javascript - Webpage contents to String

I'm currently playing around with JavaScript attempting to fetch the contents of a webpage as plain text, and dump the text to a String.

I have found many ways to do this but nothing seems to happen when I do something similar to this: (In this example I use a plain text file)

var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
    document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
    // As you can see I'm also spamming myself with alerts, but they also
    // just return blank.
    alert(xmlhttp.response);
}
xmlhttp.open("GET", "http://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-demo.txt", true);
xmlhttp.send();

How do I go about doing this?

Upvotes: 0

Views: 109

Answers (1)

webdeb
webdeb

Reputation: 13211

You cannot because of the Same-Origin-Policy.. otherwise each webpage could load some bank website or so.. So they (Browser vendors) implemented Same-Origin Policy.. You can access only websites which have give you access to..

just try put this in you console on stackoverflow:

  1. open devtools while you see this site
  2. put this into the console

jQuery.get('http://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-demo.txt')

Upvotes: 1

Related Questions