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.

7
  • 3
    I have to ask: why do you need this? Commented Mar 2, 2018 at 13:40
  • so you want the source code from one.js file? Commented Mar 2, 2018 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. Commented Mar 2, 2018 at 13:42
  • 1
    @Gniewomir don't trust client code. At that point you don't care what the user did. Commented Mar 2, 2018 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... Commented Mar 2, 2018 at 13:47

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

The result is empty string, because <script> tags are actually empty. Code is loaded form "src".
Okay. I'll edit my answer.
@Gniewomir, try now.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.