How to Hide JavaScript Code in View Source
This tutorial teaches how to hide JavaScript code from a web browser’s View Source
function.
The steps involve the placement of the JavaScript code in an external JavaScript file. After that, you can insert the file dynamically into the current page.
Hide JavaScript Code in View Source
-
Write the JavaScript Test Code
Write a new JavaScript code and save it with the
.js
extension. This JavaScript file will be the one that we’ll hide fromView Source
.To follow along, you can save the following JavaScript code as
test-viewsource.js
.alert('My code is not visible in View Source');
-
Prepare an HTML File
This HTML should contain what you’d like to show on the web page. Meanwhile, it’ll also contain a
<script>
tag.Write some JavaScript code within this
<script>
tag. There will be a few lines of code that will include thetest-viewsource.js
dynamically into the HTML file.As a result, you will not see the
test-viewsource.js
in the web browser’sView Source
.You can use the next HTML to follow along. Save the file as
no-viewsource.html
.<body> <main> <p>The included JavaScript code is not visible in View Source</p> </main> <script type="text/javascript"> /` * Code to hide from view source will go here. * Check the next code block. */ </script> </body>
-
Write Some JavaScript Code Between the
<Script>
TagWithin the
<script>
tag in theno-viewsource.html
file, we’ll write the code that will dynamically load thetest-viewsource.js
. The code will follow the steps outlined below.- Create a new
script
element with thedocument.createElement
method. - Set the script
type
attribute totext/javascript
. - Set the
src
attribute totest-viewsource.js
. - Append this new
script
element to the HTMLbody
element.
The code below is the implementation of these steps.
<script type="text/javascript"> let scriptElement = document.createElement("script"); scriptElement.type = "text/javascript"; scriptElement.src = "test-viewsource.js"; document.body.appendChild(scriptElement); </script>
- Create a new
-
Test the Code
Load the
no-viewsource.html
in your web browser and useView Source
on it. If you’ve done everything right, you’ll not see the code fortest-viewsource.js
.Rather, you’ll see the code that includes it dynamically into
no-viewsource.html
. The image below is an example of a sample output of what you should see in theView Source
of your web browser.
Conclusion
At this stage, the JavaScript code in test-viewsource.js
will not show up in the web browser’s View Source
. Meanwhile, anyone can write the URL of your website in their browser to see the code.
As advice, do not place any sensitive information in test-viewsource.js
.
Habdul Hazeez is a technical writer with amazing research skills. He can connect the dots, and make sense of data that are scattered across different media.
LinkedIn