How do I hide javascript code in a webpage?
Asked Answered
G

13

128

Is it possible to hide the Javascript code from the html of a webpage, when the source code is viewed through the browsers View Source feature?

I know it is possible to obfuscate the code, but I would prefer it being hidden from the view source feature.

Grandfather answered 29/7, 2011 at 6:11 Comment(11)
it clientside and so it will reside on every clients ( browsers )Stink
Why would you want to hide Javascript? It's not like you'd ever put any sensitive data that you don't want the user finding in it... Right?!Isolative
How would a browser know what Javascript to run?Ra
@PaulPRO has a good point -- why would you want to hide JavaScript? Anyone who wants to know what you're doing is ALWAYS going to be able to get your script with a few keystrokes. They won't just rely on View-Source. Anyone who doesn't know how to get a script is likely not going to be interested in it anyway.Tentation
https://mcmap.net/q/47105/-how-can-i-obfuscate-protect-javascript-closedDouma
@ Paulpro: Well, you are right and wrong both at the same time. If you are using php/mysql and making ajax calls using GET method then a hacker can track down php file from javascript/jquery source code and using DEV CONSOL can fire ajax an event with GET data with malicious content which can mess up everything in mysql database.Unlay
Why can't you put inside the canvas tag.?Encampment
Use Encode.js : encodejs.devincity.comIronware
@UdayHiwarale It is very easy to see what are the GET and other HTTP queries performed by the client (just open the dev console and go to the network tab). When developing a website, you should assume on the server that all requests are forged by an attacker — and therefore you must validate all data, and carefully escape every string which you splice into SQL or other code.Merth
It is indeed possible, using a relatively simple method. See my answer to this thread: #6336144Nova
PHP files are secret because they run on the server, and even error messages and debugging is under the control of the developer. A similar secret solution for JS and CSS files appears to be very difficult, and may require help from browsers.Cuisine
Z
184

I'm not sure anyone else actually addressed your question directly which is code being viewed from the browser's View Source command.

As other have said, there is no way to protect JavaScript intended to run in a browser from a determined viewer. If the browser can run it, then any determined person can view/run it also.

But, if you put your JavaScript in an external JavaScript file that is included with:

<script type="text/javascript" src="http://mydomain.example/xxxx.js"></script>

tags, then the JavaScript code won't be immediately visible with the View Source command - only the script tag itself will be visible that way. That doesn't mean that someone can't just load that external JavaScript file to see it, but you did ask how to keep it out of the browser's View Source command and this will do it.

If you wanted to really make it more work to view the source, you would do all of the following:

  1. Put it in an external .js file.
  2. Obfuscate the file so that most native variable names are replaced with short versions, so that all unneeded whitespace is removed, so it can't be read without further processing, etc...
  3. Dynamically include the .js file by programmatically adding script tags (like Google Analytics does). This will make it even more difficult to get to the source code from the View Source command as there will be no easy link to click on there.
  4. Put as much interesting logic that you want to protect on the server that you retrieve via AJAX calls rather than do local processing.

With all that said, I think you should focus on performance, reliability and making your app great. If you absolutely have to protect some algorithm, put it on the server, but other than that, compete on being the best at what you do, not by having secrets. That's ultimately how success works on the web anyway.

Zealand answered 29/7, 2011 at 6:20 Comment(5)
Nice way to address the question directly. Using JavaScript to generate the <script> would keep it out of the View Source better (still visible under the live DOM) -- that is, it can't just be "right clicked on" in the Source View. It might be possible for said <script> element to be removed once the JavaScript is executed making it slightly more cumbersome (but not impossible) to get the original code... of course the net traffic will show up very readily in Firebug or similar ;-)Tokyo
@Quentin - your view-source URL is silly - that's not what's being asked or proposed here. Any person can view the code. I've said that as much as anyone else. The question is only how easy it is and, per the specific question asked, how visible it is when someone does View Source? My suggestion makes it one step removed from View Source - that's all, but it's a valid extra step.Zealand
fetch("SCRIPT TO HIDE URL or DATAURL").then(function(t) { return t.text()||false; }).then(c=>self[atob("ZXZhbA")](c))Freestone
I think we can alos add oncontextmenu = 'return false;' within html tag.Storms
@Storms - That tries to stop right-click menu, but doesn't stop all the other ways one can view the source of the page.Zealand
I
39

No, it isn't possible.

If you don't give it to the browser, then the browser doesn't have it.

If you do, then it (or an easily followed reference to it) forms part of the source.

Inexpiable answered 29/7, 2011 at 6:13 Comment(4)
I'm not sure this answer really answered the question being asked (even though it got 10 upvotes in 15 mins). They asked how to keep the code out of the browsers View Source command. That is possible. See my answer below. They didn't ask how to keep the code from being viewed by a determined hacker.Zealand
It doesn't take much in the way of determination to click the link in the View Source for an HTML document to get to the View Source for the script.Inexpiable
In my view question has not been interpreted correctly. Creating a JS file is common, what user want here (I think) is how to hide any JS variable value when any one choose option "view page source". +1 from my side.Sclerosed
This answer doesn't make any sense. it is better to give a suggestion here. Better option to use an external file.Furthermore
J
21

My solution is inspired from the last comment. This is the code of invisible.html

<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript" src="invisible_debut.js" ></script>
<body>
</body>

The clear code of invisible_debut.js is:

$(document).ready(function () {
var ga = document.createElement("script"); //ga is to remember Google Analytics ;-)
ga.type = 'text/javascript';
ga.src = 'invisible.js';
ga.id = 'invisible';
document.body.appendChild(ga);
$('#invisible').remove();});

Notice that at the end I'm removing the created script. invisible.js is:

$(document).ready(function(){
    alert('try to find in the source the js script which did this alert!');
    document.write('It disappeared, my dear!');});

invisible.js doesn't appear in the console, because it has been removed and never in the source code because created by javascript.

Concerning invisible_debut.js, I obfuscated it, which means that it is very complicated to find the url of invisible.js. Not perfect, but enought hard for a normal hacker.

Jeavons answered 19/11, 2013 at 22:33 Comment(3)
The strange thing is that I followed exactly the steps and I'm able to find invisible.js in sources. Chrome Version 34.0.1847.131 mAmerica
@Boyang, its just not appear in console, but if we know the path, we still able to find it.Zacarias
Not only that but it will always show up in the Network tab of most DevTools. Again every self-respecting hacker will have DevTools available.Isocyanide
K
15

Use Html Encrypter The part of the Head which has

<link rel="stylesheet" href="styles/css.css" type="text/css" media="screen" />
<script type="text/javascript" src="script/js.js" language="javascript"></script>

copy and paste it to HTML Encrypter and the Result will goes like this
and paste it the location where you cut the above sample

<Script Language='Javascript'>
<!-- HTML Encryption provided by iWEBTOOL.com -->
<!--
document.write(unescape('%3C%6C%69%6E%6B%20%72%65%6C%3D%22%73%74%79%6C%65%73%68%65%65%74%22%20%68%72%65%66%3D%22%73%74%79%6C%65%73%2F%63%73%73%2E%63%73%73%22%20%74%79%70%65%3D%22%74%65%78%74%2F%63%73%73%22%20%6D%65%64%69%61%3D%22%73%63%72%65%65%6E%22%20%2F%3E%0A%3C%73%63%72%69%70%74%20%74%79%70%65%3D%22%74%65%78%74%2F%6A%61%76%61%73%63%72%69%70%74%22%20%73%72%63%3D%22%73%63%72%69%70%74%2F%6A%73%2E%6A%73%22%20%6C%61%6E%67%75%61%67%65%3D%22%6A%61%76%61%73%63%72%69%70%74%22%3E%3C%2F%73%63%72%69%70%74%3E%0A'));
//-->

HTML ENCRYPTER Note: if you have a java script in your page try to export to .js file and make it like as the example above.

And Also this Encrypter is not always working in some code that will make ur website messed up... Select the best part you want to hide like for example in <form> </form>

This can be reverse by advance user but not all noob like me knows it.

Hope this will help

Kloster answered 15/12, 2012 at 11:23 Comment(2)
Your provided link is not open give 404 code error.Bumblebee
This same approach is how Site Hackers inject malicious code into a website. Some of the more advanced Security Web Crawler tools look for code like this and sanitize it out of the page source.Isocyanide
R
11

'Is not possible!'

Oh yes it is ....

//------------------------------
function unloadJS(scriptName) {
  var head = document.getElementsByTagName('head').item(0);
  var js = document.getElementById(scriptName);
  js.parentNode.removeChild(js);
}


//----------------------
function unloadAllJS() {
  var jsArray = new Array();
  jsArray = document.getElementsByTagName('script');
  for (i = 0; i < jsArray.length; i++){
    if (jsArray[i].id){
      unloadJS(jsArray[i].id)
    }else{
      jsArray[i].parentNode.removeChild(jsArray[i]);
    }
  }      
}
Reynold answered 24/1, 2013 at 6:55 Comment(4)
Very good answer. It indeed hide the javascript usage, however, only when you use the Element Inspector/Developer Tools, you can still see if you look via View Source. (At least on chrome)Swoosh
is the variable "head" redundant here or does it serve some important function?Huan
it hides it only partially... any exposed function (global) can be shown by dev tools and it will appear as an anonymous function but dev tools tells you everything including where it was loaded fromFreestone
this only hides it from source.. an anynomous function would just do the same: fetch("SCRIPT TO HIDE").then(function(t) { return t.text()||false; }).then(c=>self[atob("ZXZhbA")](c))Freestone
D
10

I'm not sure there's a way to hide that information. No matter what you do to obfuscate or hide whatever you're doing in JavaScript, it still comes down to the fact that your browser needs to load it in order to use it. Modern browsers have web debugging/analysis tools out of the box that make extracting and viewing scripts trivial (just hit F12 in Chrome, for example).

If you're worried about exposing some kind of trade secret or algorithm, then your only recourse is to encapsulate that logic in a web service call and have your page invoke that functionality via AJAX.

Dying answered 29/7, 2011 at 6:17 Comment(1)
Let's say you are worried about exposing a secret. Let's say you put it into a PHP file and call it via Ajax. Then anyone can call that PHP file and find the secret. There is probably a way to protect secrets using PHP, and I've been struggling to find it. Generate a random number and require that all assets supply it as an argument to the PHP file. I think this works, but not if a malicious user uses developer tools.Cuisine
K
5

I think I found a solution to hide certain JavaScript codes in the view source of the browser. But you have to use jQuery to do this.

For example:

In your index.php

<head>
<script language = 'javascript' src = 'jquery.js'></script>
<script language = 'javascript' src = 'js.js'></script>
</head>

<body>
<a href = "javascript:void(null)" onclick = "loaddiv()">Click me.</a>

<div id = "content">
</div>

</body>

You load a file in the html/php body called by a jquery function in the js.js file.

js.js

function loaddiv()
{$('#content').load('content.php');}

Here's the trick.

In your content.php file put another head tag then call another js file from there.

content.php

<head>
<script language = 'javascript' src = 'js2.js'></script>
</head>

<a href = "javascript:void(null)" onclick = "loaddiv2()">Click me too.</a>

<div id = "content2">
</div>

in the js2.js file create any function you want.

example:

js2.js

function loaddiv2()
{$('#content2').load('content2.php');}

content2.php

<?php
echo "Test 2";
?>

Please follow link then copy paste it in the filename of jquery.js

http://dl.dropbox.com/u/36557803/jquery.js

I hope this helps.

Kenning answered 7/11, 2012 at 3:59 Comment(1)
This will provide only minimal protection. It's trivial to go to the browser's dev tools' network tab and see all downloaded scripts, including those loaded through Ajax.Phenylamine
R
4

Is not possbile!

The only way is to obfuscate javascript or minify your javascript which makes it hard for the end user to reverse engineer. however its not impossible to reverse engineer.

Riemann answered 3/8, 2012 at 9:11 Comment(0)
C
4

You could use document.write.

Without jQuery

<!DOCTYPE html>
<html>
<head><meta charset=utf-8></head>
<body onload="document.write('<!doctype html><html><head><meta charset=utf-8></head><body><p>You cannot find this in the page source. (Your page needs to be in this document.write argument.)</p></body></html>');">
</body></html>

Or with jQuery

$(function () {
  document.write("<!doctype html><html><head><meta charset=utf-8></head><body><p>You cannot find this in the page source. (Your page needs to be in this document.write argument.)</p></body></html>")
});
Christiachristian answered 1/12, 2013 at 20:35 Comment(0)
I
0

Approach i used some years ago -

We need a jsp file , a servlet java file and a filter java file.

Give access of jsp file to user. User type url of jsp file .

Case 1 -

  • Jsp file will redirect user to Servlet .
  • Servlet will execute core script part embedded within xxxxx.js file and
  • Using Printwriter , it will render the response to user .

  • Meanwhile, Servlet will create a key file .

  • When servlet try to execute the xxxx.js file within it , Filter
    will activate and will detect key file exist and hence delete key
    file .

Thus one cycle is over.

In short ,key file will created by server and will be immediatly deleted by filter .

This will happen upon every hit .

Case 2 -

  • If user try to obtain the page source and directly click on xxxxxxx.js file , Filter will detect that key file does not exist .
  • It means the request has not come from any servlet. Hence , It will block the request chain .

Instead of File creation , one may use setting value in session variable .

Intrigante answered 8/11, 2019 at 9:26 Comment(0)
E
0

Put your JavaScript into separate .js file and use bundling & minification to obscure the code.

http://www.sitepoint.com/bundling-asp-net/

Elmaelmajian answered 18/11, 2020 at 10:4 Comment(0)
S
0

It's possible. But it's viewable anyway.

You can make this tool for yourself:

const btn = document.querySelector('.btn');
btn.onclick = textRead;
const copy = document.querySelector('.copy');
copy.onclick = Copy;
const file = document.querySelector('.file');
file.type = 'file';
const pre = document.querySelector('.pre');

var pretxt = pre;

if (pre.innerHTML == "") {
    copy.hidden = true;
}

function textRead() {
    let file = document.querySelector('.file').files[0];
    let read = new FileReader();
    read.addEventListener('load', function(e) {
        let data = e.target.result;
        pre.textContent = data;
    });
    read.readAsDataURL(file);
    copy.hidden = false;
}

function Copy() {
    var text = pre;
    var selection = window.getSelection();
    var range = document.createRange();
    range.selectNodeContents(text);
    selection.addRange(range);
    document.execCommand('copy');
    selection.removeAllRanges();
}
<input class="file" />
<br>
<button class="btn">Read File</button>
<pre class="pre"></pre>
<button class="copy">Copy</button>

How to use this tool?

  1. Create a JavaScript file.
  2. Go in the tool and choose your JavaScript file.
  3. Copy result.
  4. Paste the result in Notepad.
  5. Remove data:text/javascript;base64,.
  6. Paste eval(atob('Notepad Text')) to your code and change Notepad Text to your Notepad text result.

How to view this hidden code?

  1. Copy the hidden code and paste it in Notepad.
  2. Copy a string that after eval and atob.
  3. Paste data:text/javascript;base64,String and change String to your copied string.
Salverform answered 4/1, 2021 at 12:27 Comment(0)
M
0

This question, which is paradoxical in nature; why? Because you are asking how, or for code, from guys who want to hide code. And if they really knew or wanted to hide code I don't think in all honesty the "best source" would outright tell you because a... they don't want to reveal their secrets?, HAHA! But maybe I am not the best source because I am going to tell you how I do this in a "general" sense. So, touché to myself.

At any rate: the quickest answer would be to have your code and use a WebSocket (or similar approach) that when a user clicks an element or double clicks (etc) you send over the js code and inject it, then do clean up. You would need some minor javascript code to handle the juggling and basic utility to get the ball rolling but the rest of 75% or more of you code could be obfuscated...

Sucks to have to have a server inject minor code fragments every time an event-like task happens but your code won't be in a file unless some kind of logging or tracking of events is happening but at least it wouldn't be a blatant file.

But here is the problem, I am answering your question like someone else mentioned, pertaining to javascript, which is to hide the javascript; the way I actually do this is to forgo the js and when a user clicks I perform a WebSocket fetch, and my server is informed of who and what they did and want, then the server in turn on server side modifies the element and sends the element update back.

This is mainly for a game interface I am working with and having a WebSocket might be too much. So... 2¢?🤷🏻

Marquardt answered 29/1 at 4:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.