Home > Back-end >  HTML Include Script Backwards
HTML Include Script Backwards

Time:10-07

I know that one can include JS in their HTML files with a <script src=""></script> include, but can you specify it to load in the script src backwards (reading line by line bottom to top instead of top to bottom)? I would not like to include the script src with any inline JS or anything like that: it needs to be simply included in (but from bottom to top instead of top to bottom). Further, I understand I could just flip the script around so that loading it top to bottom isn't an issue, but I would like to know if there is any way I could simply load from bottom to top.

For example, here's a test.js file:

alert("line 1!");
alert("line 2!");
alert("line 3!");

And if I include it in a test.html file, I could do this in the <head></head> or <body></body>:

<script src="test.js"></script> <!-- Assuming They are in the same directory -->

Now when this test.js gets included, it is (as far as I am aware) going to read test.js from top to bottom, so alert("line 1!") will run before alert("line 3!"). And, if let's say line 1 in test.js is invalid, then the whole script stops getting included. I am wondering if I can do a <script src="test.js"></script> include where line 3 (the last line) gets read first (so alert("line 3!")) and the first line gets read last (alert("line 1!")). I am doing a cyber security challenge and I know that the top of the file I am trying to include is not valid JS, but the bottom is, so theoretically if I can include it from bottom to top I could get my JS to execute before it throws an error.

CodePudding user response:

You can create a function that executes the script contents backward by sending an AJAX request to the target URL, splitting the response by a newline, reversing the resulting array, join into a string then use eval.

Something like this:

function loadScriptBackwards(url) {
  var xhttp;
  xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      eval(this.responseText.split("\n").reverse().join('\n'))
    }
  };
  xhttp.open("GET", url, true);
  xhttp.send();
}
  • Related