-1

I am trying to create a web page that opens another web page when you click the "Try It" button, and then counts the number of characters in that webpage. Right now, this web page successfully opens the web page I ask it to open, but the length of the web page in characters is "undefined". I do not want to get rid of the XMLHttpRequest or the line of code below it, because I am planning to expand this webpage to enable it to parse the webpage by certain specific keywords later. Here is the code:

<!DOCTYPE html>
<html>
<body>

<p>Click the button to open a new browser window.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    window.open("https://www.gutenberg.org/files/1065/1065-h/1065-h.htm");
    var req = new XMLHttpRequest();
    req.open('GET', 'https://www.gutenberg.org/files/1065/1065-h/1065-h.htm', false);
    alert(req.length);
}
</script>

</body>
</html>

Any assistance that anyone can provide me would be greatly appreciated. Have a nice day.

DED1
  • 43
  • 6

1 Answers1

0

First of all you need a flag header in the remote server that allow your url to make XMLHttpRequests. Access-Control-Allow-Origin: * or Access-Control-Allow-Origin: yoururl.com

Another problem is that https version has a redirect to http version, then you could have problems if you are executing this from a https site, because of "mixed content" behaviour of client's browsers. Also synchronous XMLHttpRequest (false flag) is deprecated or going to be deprecated soon https://xhr.spec.whatwg.org/ .

If you perform this in the same domain (http gutenberg) it works. You should try executing this in your http server, and looking the console expecting not to have Access-Control-Allow-Origin restriction.

var req = new XMLHttpRequest();
req.open('GET', 'http://www.gutenberg.org/files/1065/1065-h/1065-h.htm', true);
req.onreadystatechange = function (aEvt) {
  if (req.readyState == 4) {
     if(req.status == 200)
      console.log(req.responseText);
     else
      console.log("Error loading page\n");
  }
};
req.send(null)
Emeeus
  • 5,072
  • 2
  • 25
  • 37
  • I pasted in all the code that you added, but now the pop-up does not even appear. I put the line of code for the pop-up right underneath the req.send(null) line of code, and now it doesn't work. Do you have any advice for me as to how I can get the line alert(req.length) to work? Thank you for your help. – DED1 May 11 '18 at 15:17
  • Press F12 in your browser and read errors, almost certainly you have one of errors described above. Access-Control-Allow-Origin error has no solution unless you ask gutenberg to add your url. To count characters, then you need some server logic, like curl instead of ajax. – Emeeus May 11 '18 at 15:24
  • Now I know what the best solution to my problem is. Thank you very much. – DED1 May 12 '18 at 03:30