How do I hide javascript code in a webpage? - javascript

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.

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:
Put it in an external .js file.
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...
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.
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.

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.

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.

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

'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]);
}
}
}

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.

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>
Click me.
<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>
Click me too.
<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.

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>")
});

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.

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 .

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?
Create a JavaScript file.
Go in the tool and choose your JavaScript file.
Copy result.
Paste the result in Notepad.
Remove data:text/javascript;base64,.
Paste eval(atob('Notepad Text')) to your code and change Notepad Text to your Notepad text result.
How to view this hidden code?
Copy the hidden code and paste it in Notepad.
Copy a string that after eval and atob.
Paste data:text/javascript;base64,String and change String to your copied string.

Put your JavaScript into separate .js file and use bundling & minification to obscure the code.
http://www.sitepoint.com/bundling-asp-net/

Related

Write a js script in a div

I am trying to get a script from another website using jQuery then document.write it
here is my code
var url = "https://code.jquery.com/jquery-1.10.2.js";
var dam = $.getScript(url);
document.write(dam);
But this doesn't work!!
all what I get on the page is [object Object]
Can this be achieved without XHR?
jsfiddle
Don't use document.write, it does not do what you think it does. What it does not do is write some data at the end of the document. What it does instead, is pipe data into the current write stream. And if there is no write stream, it will make a new one, resetting the document's content. So calling document.write(dam) means you just wiped your document. document.write is a low level JS function from an earlier era of JavaScript, don't use it.
Instead, you want to use modern DOM manipulation functions, so in jQuery, that's stuff like:
$(document.head).append($("<script>").attr("src", url));
where
$("<script>")
builds a new script element,
$(...).attr("src", url)
sets the "src" attribute to what you need it to be, and:
$(document.head).append(...)
or
$(document.body).append(...)
to get the script loaded into your document. If it's a plain script with src attribute, it can basically go anywhere, and if it's a script with text content that should run, you can only make that happen through document.head.
Although if it's just a script you need to load in and run, you can use getScript, but then you don't need to do anything else, it's just:
var url = "https://code.jquery.com/jquery-1.10.2.js";
jQuery.getScript(url);
Done, jQuery will load the script and execute it. Nothing gets returned.
Of course, the code you're showing is loading jQuery, using jQuery, so that's kind of super-odd. If you just want to load jQuery on your page, obviously you just use HTML:
<!doctype html>
<html>
<head>
...
</head>
<body>
...
<script src="http://https://code.jquery.com/jquery-1.10.2.js"></script>
</body>
</html>
with the script load at the end so the script load doesn't block your page. And then finally: why on earth are we loading jQuery version 1.x instead of 2.x? (if you need to support IE8: that's not even supported by Microsoft anymore, so you probably don't need to).
And finally, if we don't want to load the script, but we really just want its content, as plain text, there's only a million answers on Stackoverflow already that tell you how to do that. With jQuery, that's:
$.get("http://https://code.jquery.com/jquery-1.10.2.js", function(data) {
$(document.body).append($("div").text(data));
});
But you knew that already because that's been asked countless times on Stackoverflow and you remembered to search the site as per the how to ask instructions before asking your question, right?
executing the script on the page is not my goal!. I want to get the
script content and put it a div (USING JAVASCRIPT - NO XHR) , is that
possible ?
Try utilizing an <iframe> element
<div>
<iframe width="500" height="250" src="https://code.jquery.com/jquery-1.10.2.js">
</iframe>
</div>
jsfiddle http://jsfiddle.net/snygv469/3/
Make it easier... use my fiddle
http://jsfiddle.net/wwwfzya7/1/
I used javascript to create an HTML element
var url = "https://code.jquery.com/jquery-1.10.2.js";
var script = document.createElement("SCRIPT"); //creates: <script></script>
script.src = url; //creates: <script src="long_jquery_url.js"></script>
document.body.appendChild(script); //adds the javascript-object/html-element to the page.!!!
Use this way, it can fix your problems.
$.get( "https://code.jquery.com/jquery-1.10.2.js", function( data ) {
alert(data);
});
You can try adding
<script src="http://code.jquery.com/jquery-1.8.3.min.js" ></script>
Then an AJAX call, but it pulls data from CACHE. It looks like an AJAX but when <script> is added file goes in cache, then read from cache in the ajax. In cases where it is not stored in cache read it using normal AJAX.
jQuery.cachedScript = function(url, options) {
// Allow user to set any option except for dataType, cache, and url
options = $.extend(options || {}, {
dataType: "text",
cache: true,
url: url
});
// Use $.ajax() since it is more flexible than $.getScript
// Return the jqXHR object so we can chain callbacks
return jQuery.ajax(options);
};
$(document).on('ready', function() {
// Usage
$.cachedScript("http://code.jquery.com/jquery-1.8.3.min.js").done(function(script, textStatus) {
console.log(script);
});
});
Normal Solution
If you are ready to use AJAX look at this fiddle
How to fetch content of remote file and paste it on your document and execute that js code
I guess you want to get content written on remote file and want to write that content in your HTML. to do this you can use load() function.
To do this follow the following steps:
1. Create a file index.html Write the following code in it:
<pre id="remote_script"></pre>
<script>
$(document).ready(function() {
//var url = "https://code.jquery.com/jquery-1.10.2.js";
var url = "remote_script.html";/* For testing*/
$('#remote_script').load(url,function(){
eval($('#remote_script').text()); /* to execute the code pasted in #remote_script*/
});
});
</script>
2. Create another file remote_script.html for testing write alert('a'); in it without any <script> tag and run the above code.

How to implement the "Pin it" function from pinterest

I'm trying to make a new pin it button just like Pinterest has, I've see the content at that bookmark:
javascript:void(
(function(){
var e=document.createElement('script');
e.setAttribute('type','text/javascript');
e.setAttribute('charset','UTF-8');
e.setAttribute('src','http://assets.pinterest.com/js/pinmarklet.js?r='+Math.random()*99999999);
document.body.appendChild(e)
})()
);
I'm new to javascript, so I am not sure how to start to do a new one. I have even no idea where should I start my coding. Is the backend for this Pin it button limited? Can anyone introduce how does this Pin it button works? Thank you so much.
Basically what that code does is injects a <script> tag into the page. The actual "pin it" code is located in the pinmarklet.js file.
To make your own feature like this, you can just reuse the code and replace the source with your own JavaScript file.
Side-note: the void(...) part is redundant because the function doesn't return anything anyway.
The code you posted simply injects a JavaScript file into the page's DOM which will cause it to get interpreted by the JavaScript engine. What you should be more interested in is the code in this file which implements the "Pin It" functionality:
http://assets.pinterest.com/js/pinmarklet.js
But since that is minified and somewhat obfuscated and probably proprietary, I would suggest what you want first is an easy to follow tutorial on how to create a Bookmarklet:
http://betterexplained.com/articles/how-to-make-a-bookmarklet-for-your-web-application/
Then, you need to think about how you will code your own web application to respond to asynchronous requests to "Pin" or save something. The following two simple but useful JavaScript variables could come in handy if you're just going for a simple "link-submission" type of functionality:
document.location.href -- to get the page's URL
document.title -- to get the contents of the page's TITLE tags
To compress your code into a single-line as is required by bookmarklets, you could use this tool:
http://subsimple.com/bookmarklets/jsbuilder.htm
If you want to add it to a button here is how:
html:
<button id="pintrest">Pin It</button>
And you script:
var btn = document.getElementById("pintrest");
btn.onclick = function () {
var e = document.createElement('script');
e.setAttribute('type', 'text/javascript');
e.setAttribute('charset', 'UTF-8');
e.setAttribute('src', 'http://assets.pinterest.com/js/pinmarklet.js?r=' + Math.random() * 99999999);
document.body.appendChild(e);
};
Now when you click on the button it should run the pintrest code

random quote from array in external javascript not displaying onload

I'm a javascript beginner, and I'm trying to figure out why this code works when written in the head, but not when it's being referenced from an external file.
in the head of my html document, I'm referencing the javascript file "quote.js" as follows.
<script type="text/javascript" language="JavaScript" src="/js/quote.js"> </script>
the contents of quote.js are as follows
var textarray = [
"Be Good.",
"Our future depends powerfully on how well we understand the cosmos.",
"Bottomless wonders spring from simple rules... repeated without end.",
"All our science, measured against reality, is primitive and childlike — and yet, it is the most precious thing we have.",
"To use violence is to already be defeated."
];
function RndText() {
var rannum= Math.floor(Math.random()*textarray.length);
document.getElementById('ShowText').innerHTML=textarray[rannum];
}
window.onload = function() { RndText(); }
finally, the div I'm replacing in the body is as follows...
<div id = "ShowText"></div>
it's probably a stupid mistake, but I've been trying to track it down for a while now, and I'm missing something. When I write the contents of quote.js in my html head, it works fine. Any ideas? Thanks in advance.
If the code works in the head, but not when included, it's likely to be a problem with the path to the script. Double check that /js/quote.js is an appropriate location. It may need to be js/quote.js, you you may have a typo. In browsers like FireFox and Chrome, if you view the source code of your page you can click on the path to files like this and it loads the included file or shows you an error if the file is not found.
If you can share a link to the page, I can tell you with more certainty exactly what the problem is.
Also, you don't have to the language attribute if you're using XHTML, but that's not causing the problem.
Perhaps the code is running before the DOM is ready
Instead of onload use the event DOMContentLoaded
document.addEventListener('DOMContentLoaded', function () {
//code here
}, false);

Javascript in a website

This is a basic question but google didn't provide any help.
I have a website and what to beable to run javascript on it.
In my directories I have index.html, and index.css. For the javascript file, I'm assuming it should be called index.js.
In my index.js file I have this:
var countTime = 0; // Number of seconds
var redirectURL = "http://example.com"; // URL to direct to
countTime = (countTime+1)*1000;
function updateCount(){
countTime = countTime-1000;
if(document.getElementById("countdownDisplay"))
document.getElementById("countdownDisplay").innerHTML = (countTime/1000);
if(countTime <= 0)
location.href = redirectURL;
else
setTimeout("updateCount()",1000);
}
updateCount();
However it's not working when I visit the page with a browser.
Do I have to do something in my html file like include index.js or something?
<script src="index.js" type="text/javascript"></script>
Should go in your <head>.
This will load the script for you and then the code gets executed.
Your also going to need something like
<div id="countdownDisplay"></div> in your <body> for the countdown to work.
Whilst I'm at it you probably want a
<style src="index.css" type="text/css"></style> in your <head> as well if you havn't already.
Yes, you need to include it in the HTML file. Here are some instructions.
basically when trying to write some html, you can either search on google how to write the code or as well search for a page which provides what you want to do and look into it's source. This way google would have helped you, because google uses javascript.
In addition, check your totalvalidator. It is a very useful firefox plugin for advanced html validation. It supports better evaluation than the w3c validator does.

How to embed and call a javascript script in a RichFaces/JSF page

I've been looking around for a method to embed and call javascript functions in JSF pages. I'm also using RichFaces.
To define the function, it appears I can do this in a cross-browser supported fashion:
<a4j:outputPanel ajaxRendered="true">
<f:verbatim>
<script type="text/javascript">
function datum() {
alert("hi");
}
</script>
</f:verbatim>
</a4j:outputPanel>
but I'm not sure how I can call this function when the page loads so the text it returns is embedded in an h:outputPanel. The plan is to have a js clock embedded in the page which is served to the client. Note I'm not using the body tag, I'm using facelets ui:composition, f:view (core) and RF RI rich:page.
Thanks
Regardless of what sorts of server-side tags you're using, by the time your page gets to the browser that's all gone and it's just HTML. (At least, it had better be, or things won't work anyway.) What you need to do is arrange for your code to be called by a "load" event handler. There are various ways to do this, but the simplest would be this:
<f:verbatim>
<script type="text/javascript">
window.onload = function() {
alert("hi");
}
</script>
</f:verbatim>
Now as to initializing another part of the page, once again what matters is what ends up in the HTML. You'll want to arrange for there to be some sort of HTML container (a <div> or something, depending on your page design) and you'll want it to have a unique "id" attribute. Your Javascript can then use the "id" to find the element and set its contents:
var elem = document.getElementById("whatever");
elem.innerHTML = // ... whatever ;
You'd probably do that stuff inside the "load" function.
Also, if you're using Facelets instead of JSP, which is a XML based view technlogy, you will need to add the XML CDATA section delimiters if your JavaScript contains comments // or literals such as <, >, &&, etc. Here's the example with the XML CDATA delimiters:
<f:verbatim>
<script type="text/javascript">
//<![CDATA[
//Comments won't show error now.
window.onload = function() {
alert("hi");
}
//]]>
</script>
</f:verbatim>
You can see a thorough explanation of when to use CDATA here. You do not need those if you're creating HTML5 pages.
Happy coding!

Categories

Resources