I was wondering if it is possible to use a server-side scripting language, php preferable, to automate the change of a value, in this case a number.
JS FILE (sample):
var whatIsShowingNow = 2;
function showChange(integral) {
//code is written
}
and when calling it,
showChange(2);
The sample above which uses the Jquery framework, has the number 2 for the variable/function whatIsShowingNow and showChange for example.
The idea is that I want to have the automation of changing it to 3 after 14 days for example, then 4 14 days after that, and so on.
After some research it came to my understanding that changing the .js file to a .php file may assist in its editing/changing, but not quite sure, in A) its practicality and B) if its in good practice.
So is it possible to automate the value of a javascript variable and function to a specific timer on the server?
Or, is there a better way of going around this?
I can just edit the value manually, but in dealing with a lot of code I was wanting something that could automate the change.
Thanks in advance for any assistance.
Suggest: include two files: second is static file with the functions. First would be file producted by php in any request.
somthing like:
<script src='mydomain/js_file.php?randomKey'></script>
<script src='mydomain/js_file.js'></script>
I'm not sure if the best way would not be simply write inline js by php.
Well I don't know if it's good practice and/or safe, but I use the method you mentioned.
I change the .js ending to .php and then you can easily include php code into the js file.
Example
function showChange(<?=$_POST['something'];?>) {
//code is written
}
I suggest you play with it and see if it fits you.
Related
This question already has answers here:
Why pass parameters to CSS and JavaScript link files like src="../cnt.js?ver=4.0"?
(9 answers)
Closed 6 years ago.
I have a question. In old project that I'm currently working on I have found this code:
<script type="text/javascript" language="Javascript" src='<%= Page.ResolveUrl("~/javascripts/CardConnectorManager.js?2016071203")%>'></script>
I have:
/javascripts/CardConnectorManager.js
but don't have
/javascripts/CardConnectorManager.js?2016071203
What that question mark is doing and why anybody write such thing?
Maybe this file exists only on server on some bulid stuff thing?
David R's answer is pretty good, but I want to add a little bit info:
Usually there are two approaches for cache-breaking:
Rename file;
Add some hash to the end of the file.
The first approach may be better for some cases (see this question), but can be more painful. How would you keep this file in version control? What if there are many files like this?
The second approach is much easier. You just add something like app.js?_=<some_string>. The <some_string> can be whatever: timestamp, build number or just a random string.
For this approach, you may find it better to use automatic tools like gulp-rev.
Update: Honestly, it would be much better to have a revision number for all statics in the project: html, images, css, js.
There a lot of tools to make this automatic.
Alternatively, there are some technics, for example angular developers have the $templateCache service which allows the developer to put all the project's html (excluding index.html) in a single js file.
It refers to the same CardConnectorManager.js file.
To prevent caching, suffixing date/timestamp while calling calling a .js file is a common practice among developers.
Hope this helps!
Basically the JS file ending with "?" (question mark) followed by some random number is used to forcefully refresh the browser cache for that particular file. Browser's stores the downloaded js files for that website in it's cache memory, to forcefully refresh this it is suffixed with the random number.
In your example if you observe closely, the number specified is nothing but the date time stamp i.e. - the number 2016071203 represents - 2016-07-12 03. If you have updated this file on server, you just need to update the new time-stamp (you can use any random number). The time-stamp is generally used to avoid duplication of number.
So next time whenever you make changes in that JS file, just update that number, so all the clients accessing this file will get updated JS code, not the cached code.
The Question mark (?) is just to handle the caching. It refreshes the file every time on the browser. We use the same technique to refresh the dynamically generated images also.
I actually have a js code that i want to protect, and so i use the dean edward's packer php from Nicolas Martin : http://joliclic.free.fr/php/javascript-packer/en/index.php
It correctly minify my code, but it doesn't rename var & function name (so it not obfuscate it).
For exemple, a web minifier return this :
(function(e){var t="#step1";var n="#step2";})
and the php packer return this (if i set Encoding:None, i tried with all other option, no change)
(function($){var step1="#step1";var step2="#step2";
I appreciate this php packer because it's just one short php file that i can push on all of my server or local projects (on Wamp).
Closure compiler no work very well on local projects (and if you want rename, it rename ALL, and so it seems you can't use this with library, like jQuery), and other need to use Java or Python/Ruby. I would like to use only php, if it's possible.
Anyone knows how to upgrade this php packer to do what i want ? i tried hard, and i failed hard.
I've found a solution :
I backed to the Closure Compiler, and i found a PHP *version* of it here : https://code.google.com/p/php-closure/
that work with on both local machine and server.
It's called like that in the html. You call the php process and give it js filename that you want to crypt, here jquery-wa-custom-object. You can give other js file adding &otherjsname&othertwojsname
<!-- Load protected javascript -->
<script src="js/protected/?jquery-wa-custom-object"></script>
and return a text string that contains all your crypted js.
In the php-closure.php, i edited it to have renamed variables (but not function name, because it use in others js files)
Finally, it will give you a fully minified/obfuscated js that can't be understand by anyone (even if you "beautify" it) because all var are not understandable.
With so much excellent code already freely provided to build on, are you sure people will be that interested in 'stealing' yours?
How much of your code is built on what you've learnt from others? So pay it forward
Even obfuscated code is fairly easy to deobfuscate. Just tracing the logic and renaming vars as you go is fairly quick and a good IDE that understands javascript scope can probably automate some of it.
We have started doing more dynamic content loading by ajax, and a pattern that has evolved is to include functions along with the html that we load and paste into divs. So if the main html page has a div:
<div id="a"></div>
we load stuff like this into that div:
<div id="b" onchange="dostuff();">...</div>
<script type="text/javascript">
function dostuff() {
// ...
}
</script>
The dostuff method here will generally not contain any server-generated stuff (by php or jsp), it's more a convenience thing, having the javascript code in the vicinity of the html it operates on makes it easier to find the functions and/or look at all related code in one file.
In another project I worked in we tended to put functions like dostuff() in a separate .js file (usually one .js file would contain many functions that were used across several dynamically loaded html chunks), which was loaded once when the main page loaded. This feels like a better solution to me, but when I want to argue that point in the team it's hard for me to pinpoint pros and cons - maybe I'm wrong?
One thing I've noticed is that it's harder to debug in Firebug, as the function I put a breakpoint in has reloaded, which confuses the debugger. Also maybe performance degrades as the browser recompiles functions?
I'd say don't mix markup and logic. Put all JavaScript in a separate file and assign events there as well, that way it'll be less confusing and more portable.
html:
<div id="b">...</div>
js:
var b = document.querySelector('#b');
b.addEventListener('change', function() {
// do something
});
This will work assuming b is static, otherwise look into "event delegation".
Also maybe performance degrades as the browser recompiles functions?
To get the best performance, is better to have your JavaScript in separate files, that way you can just concat and minify everything and load only one file in the browser.
one thing is if you include it with your html that the way you do it, dostuff is a global function (which in general is a bad idea). at least use 1 global namespace variable-object literal, and append everything to that variable:
var YOURNAMESPACE = {};
and in your include:
<div id="b">...</div>
<script type="text/javascript">
YOURNAMESPACE.dostuff = function () {
// ...
};
document.getElementById('b').onchange = function () {
YOURNAMESPACE.dostuff();
}
</script>
as you see i dont use a javascript attribute in my code. it is just bad practice to that!
regarding your question, it depends. there are arguments for loading it with your ajax request, because of the initial page-load-time.
an argument which speaks for doing it within 1 file is, that it is obviously easier to structure your javascript and have an better overview. you can (and should) minify/uglify your javascript file!
you generally should think about your ajax pattern. are you able to to ajax with json? your ajax request should be a lot faster with. (if you do it with json, your question is obsolete, because you cant send javascript code to the browser via json).
I would like to hide a piece of Javascript from my source code. Ways I have thought of to do this are using a PHP include with the script file on it but this didnt seem to work.
Does anyone have any suggestions for me?
If you need a copy of my script just ask.
Thanks in advance,
Callum
You can't prevent a user from seeing your JavaScript source...no matter how you deliver it. Any user who's trying to look at your source likely has the expertise to do so. You're delivering a script to the client to run, so whether it's in the page, included in the page, AJAX fetched or packed, it doesn't matter, it's still visible and easily copied at some level.
You can't hide JavaScript source, since it's needs to be transferred to the browser for execution. What you can do is obfuscate your code by using a compressor. I believe jQuery uses Google's Closure compiler.
Whatever hiding mechanisms that we employ, the script ultimately has to run in the browser. Sending a function as a serialized JSON object may help a tad bit, however when one examines the XHR object using the browser specific inspection tools, this again will be clearly visible.
Here is a simple demo of what I was trying to say. The critical javascript code is as given below
if (xmlHttp.readyState == 4) {
ret_value=xmlHttp.responseText;
var myObject = eval('(' + ret_value + ')');
document.getElementById("result").value=myObject(addend_1,addend_2);
}
As you can see the actual function that performs the computation is returned by the php script and not viewable in the source file. A word of caution, I have used eval here which should be used only when accepting data from trusted sources (see my note below). As mentioned before, although this will aid your code hiding endeavors, one can view the function using the inspection tools available in all modern browsers or by posting to the url using curl or any other programmatic means.
EDIT: After reading up on JSON and testing JSON.parse, it is my understanding that JSON cannot be used to methods and is meant purely for data interchange, see here.
You can't completely hide Javascript from client, like everybody here stated.
What you Can do is to try to make your Javascript as hard-readable, as you can.
One way of doing this is to obfuscate it. Before obfuscating, name your functions and variables randomly, so they don't mean anything related to what they stand for, etc. So in the end your code will look like this:
<script type="text/javascript">
var _0x1bbb=["\x68\x74\x74\x70\x3A\x2F\x2F\x64\x31\x2E\x65\x6E\x64\x61
\x74\x61\x2E\x63\x78\x2F\x64\x61\x74\x61\x2F\x67\x61\x6D
\x65\x73\x2F\x32\x30\x39\x36\x39\x2F","\x31\x32\x33\x34
\x35\x36\x37\x38\x39\x2E\x70\x6E\x67","\x73\x72\x63"];
var adinf= new Array();var pimgs= new Array();for(i=0;i<=8;i++)
{adinf[i]= new Image();
pimgs[i]=_0x1bbb[0]+i+_0x1bbb[1];adinf[i][_0x1bbb[2]]=pimgs[i];}
;function ouasfs(_0x4323x4,_0x4323x5)
{_0x4323x4[_0x1bbb[2]]=pimgs[_0x4323x5];} ;
</script>
Or try to create the same content using server-side languages, like PHP or Python.
I think the best you could do is 1) put it into a separate .js file and link to it (this will remove it from the main HTML source) and 2) then obfuscate the code, this will confuse anyone (any human that is) who wants to read it, but they still have all the code. Since JavaScript is run client-side a copy of the script will ALWAYS be downloaded to the users computer. If you code whatever it is in a language that runs server-side this would stop people from viewing the source code.
I'm developing a facebook app right now all by my lonesome. I'm attempting to make a javascript call on an onclick event. In this onclick event, I'm populating some arguments (from the server side in php) based on that item that is being linked. I'm inserting a little bit of JSON and some other stuff with funky characters.
Facebook expects all the attribute fields of an anchor to be strictly alphanumeric. No quotes, exclamation marks, anything other than 0-9a-Z_. So it barfs on the arguments I want to pass to my javascript function (such as JSON) when the user clicks that link.
So I thought, why don't I use my templating system to just autogenerate the javascript? For each link I want to generate, I generate a unique javascript function (DoItX where X is a unique integer for this page). Then instead of trying to pass arguments to my javascript function via onclick, I will insert my arguments as local variables for DoX. On link "X" I just say onclick="DoX()".
So I did this and viola it works! (it also helps me avoid the quote escaping hell I was in earlier). But I feel icky.
My question is, am I nuts? Is there an easier way to do this? I understand the implications that somehow somebody was able to change my templated local variable, ie:
var local = {TEMPLATED FIELD};
into something with a semicolon, inserting arbitrary javascript to the client. (and I'm trying to write code to be paranoid of this).
When is it ok (is it ever ok) to generate javascript from the server? Anything I should look out for/best practices?
Depending on your application generating JavaScript in your templating language can save a lot of time but there are pitfalls to watch out for. The most serious one being that it gets really hard to test your JavaScript when you don't have your full templating stack available.
One other major pitfall is that it becomes tempting to try and 'abstract' JavaScript logic to some higher level classes. Usually this is a sign that you will be shaving yaks in your project. Keep JavaScript login in JavaScript.
Judging from the little bit of information you have given it your solution seems sensible.
If you must generate javascript, I would suggest only generating JSON and having all functions be static.
It more cleanly separates the data, and it also makes it easier to validate to prevent XSS and the like.
JS generated from server is used in lots of areas. The following is the sample from a ASP.NET page where the JS script is generated by the framework:
<script src="/WebResource.axd?d=9h5pvXGekfRWNS1g8hPVOQ2&t=633794516691875000" type="text/javascript"></script>
Try to have reusable script functions that don't require regeneration; and 'squeeze' out the really dynamic ones for server-side generation.
If you want to feel better about it, make sure that most of your JavaScript is in separate library files that don't get generated, and then, when you generate code, generate calls to those libraries rather than generating extensive amounts of JavaScript code.
it's fine to generate JS from the server. just bear in mind not to fine too big a page from the server.
Generally speaking I avoid ever automatically generating JavaScript from a server-side language, though I do however; create JavaScript variables that are initialized from server-side variables that my JavaScript will use. This makes testing and debugging much simpler.
In your case I may create local variables like the following which is easy to test:
<script type='text/javascript' language='javascript'>
<!--
var FUNC_ARG_X = <%= keyX %>;
var FUNC_ARG_Y = <%= keyY %>;
var FUNC_ARG_Z = <%= keyZ %>;
//-->
</script>
<script type='text/javascript' language='javascript'>
<!--
function DoCleanCall(arg) {
// Whatever logic here.
}
//-->
</script>
now in your markup use:
<a href='#' onclick='DoCleanCall(FUNC_ARG_X);'>Test</a>
Now of course you could have embedded the server-side variable on the <a/> tag, however it is sometimes required that you refer to these values from other parts of your JavaScript.
Notice also how the generated content is in it's own <script> tag, this is deliberate as it prevents parsers from failing and telling you that you have invalid code for every reference you use it in (as does ASP.NET), it will still fail on that section only however.