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.
Related
I am trying to install underscore.js so I can use it in my browser, but it seems all installation instructions are meant for servers. How do I use this in my web browser? I know JS has no import or require so I am not sure what to do. Thanks
Open some webpage in Google chrome or Mozilla Firefox. For example, google.com.
And then press F12 key.
Select Console Tab.And the type or Copy-paste the following code:
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js';
document.head.appendChild(script);
and press Enter.
Then start typing your underscore js commands on the console.
You don't install a JavaScript library in order to use it - you need to include it. If you have dependencies, then only the order (for example first underscore.js and then your custom library that uses underscore.js) is important.
One possibility would be to use some Content Delivery Network (CDN), so you don't need to download the library locally. Common CDN's are:
Google CDN
Microsoft CDN
cdnjs.com
If you download the library and host it on your server, than just put it in your project directory (or in a directory called scripts).
The code that includes the underscore.js library used from a custom library could look like this:
JS library demo.js
// function using underscore.js
function demo() {
var input = [1, 2, 3];
var output = _.map(input, function(item) {
return item * 2;
});
alert(input + " - " + output);
}
and then in a second file demo.html:
<!DOCTYPE HTML>
<html>
<head>
<!-- first include the underscore.js library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore.js" type="text/javascript"></script>
<!-- or if the file is downloaded locally -->
<!-- <script src="scripts/underscore.js" type="text/javascript"></script>-->
<!-- then the custom JS library -->
<script src="demo.js" type="text/javascript"></script>
</head>
<body>
<!-- call the custom library function -->
Start the script using underscore.js
</body>
</html>
The output is as expected:
1,2,3 - 2,4,6
Just paste following code into head section of your .html file.
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3 /underscore-min.js">
</script>
Please include what browser you are using, but few things come to mind:
Head over to JSFiddle or JSBin or other alternatives, include or select the JS framework you want to use and play with it.
Using JS in a browser means nothing. There's got to be some HTML code involved that could use and understand JS code.
Firefox, install addon like Firebug, open a simple page like one of SO or google.com and in the console
var script = document.createElement("script");
script.src = "http://path/to/underscor.js";
document.body.appendChild(script);
Then you could start using functions in your JS file.
Google Chrome, click F-12, go to Sources tab, click on Content Scripts in left panel, right click to add folder containing your JS files. That should work as well. There is also another sub-tab called snippets in left panel, create a new file and just copy paste entire JS file into it. Alternatively, you could follow the same technique for Firefox. Its Developer Panel is much more advanced and sophisticated.
You can try and look at things like Browserify.
The gist is, you need some kind of HTML to invoke and use JS code. IMHO, tools like JSFiddle are much better at using and testing some JS code and involves less hassle. Or just create a simple HTML file on your system, include a script tag and test it.
HTH
You should just be able to load it using a <script> tag. Looking at the code shows it will load itself into the global object (window == this).
var root = this;
...
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = _;
}
exports._ = _;
} else {
root._ = _;
}
I'm a complete newb in nodeJS, javascript and CSS. I'm currently writing a single-page application. I've added to my client side
a javascript file that contains several functions that retrieve data from the server.
In the head section of the HTML, I first load the css files and then the js file like so
<head>
...
<link rel="stylesheet" href="...">
<link rel="stylesheet" href="...">
<script src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js"></script>
<!-- ajax functions script -->
<script src="js/ajaxFunctions.js"></script>
</head>
Then, in my html, at some point, I call one of the functions in the ajaxFunctions.js like so:
<script type="text/javascript">populatePostsList()</script>
Now, the function works and retrieves the data but for some reason, when working in chrome (and chrome canary) the information is presented without the CSS styling. I have no idea why this is happening. Also, when I check it in safari it actually does work but 10% of the time, it goes back to regular html with no styling.
Has anyone ever encountered this kind of problem and can direct me in the right way?
Also, is this the best way to go about using ajax? How can I implement it so I won't
have to call the actual function but it will get called automatically when the page is first loaded?
Thanks!
I'm adding here a snippet of the populatePostsList() function.
function populatePostsList() {
var counter = 1;
$(document).ready(function() {
$.get(URLAddress + '/getPosts', {} ,function(data) {
var arr = data;
for(var i = arr.Posts.length - 1 ; i >= 0 ; i--) {
var post = arr.Posts[i];
$('#newPosts').append(// appending fields from post // );
});
});
}
Google provides its script embed code to display a trends Map by placing this code in our site.
<script type="text/javascript" src="//www.google.com.pk/trends/embed.js?hl=en-US&q=iphone&cmpt=q&content=1&cid=TIMESERIES_GRAPH_0&export=5&w=500&h=330"></script>
The above code displays the trends map.
Notice the q=iphone in the above URL. I want to pass a JavaScript variable value instead of hard coding a fixed value like iPhone in this case.
How can I use a JavaScript variable inside the src of script tag?
I tried creating script programmatically, it injects the script code but the script does not get executed.
My try
document.body.appendChild(document.createElement('script')).src= varHavingScriptURL;
My try is in a JS Fiddle here.
The problem is, you can not do this after page load. Look at the source of the script
document.write('<iframe width="500" ... </iframe>');
So you need to do this as the page is rendering because of the document.write.
Now looking at what you did
document.body.appendChild(document.createElement('script')).src = varHavingScriptURL;
That is not going to work, you need to break it up
var scr = document.createElement('script');
scr.src = varHavingScriptURL;
document.getElementsByTagName("head")[0].appendChild(scr);
but again, it is not going to work because of the document.write.
Finally after hours of struggle, I found the solution using PostScribe.
// jQuery used as an example of delaying until load.
$(function
() {
// Build url params and make the ad call
var str= "magic";
postscribe('#ad', '<script src=//www.google.com.pk/trends/embed.js?hl=en-US&q='+str+'&cmpt=q&content=1&cid=TIMESERIES_GRAPH_0&export=5&w=500&h=330><\/script>');
});
Postscribe
Working Demo
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);
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/