0

How to print all scripts code of an opened page?

All scripts are in .js local files or added by appending

document.body.appendChild(script);

I've tried to get it by var scriptList = document.scripts; or by getting nodes from HTML. All I got is object of HTMLCollection with array of scripts(without the code I need) or

<body>
    <script src="one.js"></script>
    <script src="two.js"></script>
    <script src="three.js"></script>
    <script type="text/javascript".src="https://xxx.js/"></script>
</body>

What I never get is the actual running code. Any ideas how to get it? I believe the code somewhere in browser memory, because the code is running and I can see it in inspector.

Gniewomir
  • 109
  • 11
  • 3
    I have to ask: why do you need this? – Federico klez Culloca Mar 02 '18 at 13:40
  • so you want the source code from one.js file? – moghya Mar 02 '18 at 13:41
  • I want the code of all of them combined, because they all are running. I want to hash the code and then compare it with other hash in server to ensure the user didn't edit original code. – Gniewomir Mar 02 '18 at 13:42
  • 1
    @Gniewomir don't trust client code. At that point you don't care what the user did. – Federico klez Culloca Mar 02 '18 at 13:46
  • Also, the browser can change it. Extensions can change it. And "executable code" loaded in browser memory is certainly not necessarily the source code you sent. It depends on a lot of factors. browser versions, etc... – Pac0 Mar 02 '18 at 13:47
  • @Gniewomir I think some work around browser extension API would help. – moghya Mar 02 '18 at 13:53
  • Since you don't control what happens on client's side, how would you prevent someone to temper your checking script as well, run modified javascript, but send you back the original hash of the unmodified script files ? – Pac0 Mar 02 '18 at 14:09

1 Answers1

1

Try this, now getting code from src:

var scriptList = document.scripts;

var code = "";
for (var i = 0; i < scriptList.length; i++) {
    var req = new XMLHttpRequest();
    req.onload = function () {
        code = code + req.responseText;
    }
    req.open("GET", scriptList[i].src);
    req.send();
}
alert(code);