Print a Spring variable in browser using JavaScript - javascript

I am trying to print the variable in the if condition. It's done using Spring and JavaScript. I don't know Spring. How do I print the value of a Spring variable in the browser?
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("p").click(function(){
$(this).hide();
});
});
</script>
</head>
<body>
<p>If you click on me, I will disappear.</p>
<p>Click me away!</p>
<p>Click me too!</p>
</body>
</html>

I'll be attempting to piece together my comments on your question into an answer, since they seem to have solved it.
What you should first understand is the difference between server-side code parsing and execution (a JSP page for you), and client-side code parsing and execution (HTML and JavaScript for you). You can read a brief overview in the top-rated answers to this programmers.stackexchange.com question. Further reading can be found on Wikipedia's articles on server-side scripting and client-side scripting. A key concept to take away from the client-side scripting article about server-side scripts is:
[Server-side scripts] produce output in a format understandable by web browsers (usually HTML), which is then sent to the user's computer. The user cannot see the script's source code (unless the author publishes the code separately), and may not even be aware that a script was executed. Documents produced by server-side scripts may, in turn, contain client-side scripts.
In terms of your setup, this means that when you request your JSP page via your browser, your browser tells the server that is hosting the JSP page that the browser wants that page. The server then executes the JSP page to produce a document that is purely HTML and JavaScript in nature (perhaps some CSS too, if you wrote it that way) for sending to the browser. The browser never sees the JSP code. By the time the server is done parsing and executing the JSP page, all instances of ${someExpression} (JSP EL statements) and other JSP-specific expressions (such as taglibs, like <spring:xx> tags) will be resolved to some client-side equivalent. For basic JSP EL statments (${...}), these resolve to some string value. If you happen to cleverly place that EL statement in some JavaScript in the JSP, such as console.log("${myVariable}");, then you are dynamically producing JavaScript code that will depend on the output of the EL statement (in this example, it would resolve to something like console.log("myVariable-value");).
Up to this point, the server has just been executing JSP code (and otherwise leaving HTML/JS/CSS already in the page intact). No JavaScript has been parsed or executed. This final "rendered" page, after the server is done executing JSP stuff, is then sent as purely HTML/JS/CSS to the client browser, which receives it and parses/executes it. At this point, the browser sees something like console.log("myVariable-value");, without knowing or caring that your JSP code produced it, and executes that (since you cleverly placed your EL statement to produce valid JS).
This long-winded explanation then means you can do the following:
Server-side JSP:
alert("${createBehavior.behaviorRevisionAllowed}");
Resulting code sent from the server to the client browser:
alert("false");
Result after code is executed in the browser: An alert box pops up with the value false in it.
Server-side JSP:
console.log("${createBehavior.behaviorRevisionAllowed}");
Resulting code sent from the server to the client browser:
console.log("false");
Result after code is executed in the browser: The value false is logged to the console.
Server-side JSP
return [$('#some-id'), "<spring:message code='BH-MS-0070'/>"];
Resulting code sent from the server to the client browser:
return [$('#some-id'), "some-spring-message-string"];
Result after code is executed in the browser: The array in the JavaScript return statement is created with the value "some-spring-message-string" as the second element.
From your question in your comment about an "EL variable", when I said "EL variable" I meant the fact that an EL statement, such as ${someStatement}, could be a statement as simple as a variable name, such as ${createBehavior.behaviorRevisionAllowed}. This EL statement will see just a variable name in it, attempt to find that variable and get its value, and then replace ${createBehavior.behaviorRevisionAllowed} with the actual value.
Let me know if further explanation is needed.

Related

Page does not load after calling PHP function form Javascript

When I call a PHP function from a javascript function (located in an .js external file), the webpage refreshes and appears to stop loading at the PHP function.
function completePurchase(){
//check if perosn signed in
if (signedIn){
alert("Purchase Complete! Total : " + total);
//Upadte database - call PHP function in MainPage2
document.write('<?php echo upadtePurchaseToDB();?>');
}
}
The PHP function resides in the PHP page enclosed within PHP tags:
//PHP to handle data when purchase button is pressed
function upadtePurchaseToDB(){
echo "PHP CALLAED AS PURCHASE BUTTON PRESSED";
};
The idea is to update a database when the PHP function is called.
However when called the page refreshes and remains blank.
In the console if i navigate to the 'Element' tab I can see the PHP call:
Not sure what the underlying issue is wether its how I have called the PHP function using JS or where the PHP function is placed.
One problem is that you're trying to make JS genarate PHP code, and then expecting that to work: it can't. PHP runs on the server, and only "does things" when asked for a page by the browser: PHP generates source code for the browser to deal with. That's all it does.
When the browser has the page, JS kicks in, and PHP is no longer anywhere to be found: see Difference between Javascript and PHP for more information on this, and I can strongly recommend reading up on that.
However, the real problem that you're describing (your page seemingly reloading but dying on the PHP code) is one caused by your use of document.write(), which absolute doesn't do what you think it does, and you should not be using it in modern code.
document.write is one of the earliest functions in JS and is super low level: it does not write text into a webpage, it writes bytes into the document bytestream so that the document parser can pick up data from the bytestream at the same time and parse it into a page tree.
While the page is still being processed, that seems safe: document.write will simply inject bytes into the open bytestream, and the parser will parse that, and all will seem well. However, once the page tree is done and the document bytestream gets closed, things start to go very, very wrong:
Any call to document.write will try to write into the open bytestream, and if it's closed, document.write will simply open a bytestream: now you have an empty document bytestream. And because the document parser sees an open bytestream, it start building a page tree based on what's in it, and now your page is gone because that's what you told the browser to do.
It's also not the case that it "appears to stop loading at the PHP function", what actually happens is that you've told the page parser that the new page code to form a page tree off of is the byte sequence <?php echo upadtePurchaseToDB();?>. So the parser looks at that, sees <, and so knows that what comes after that will be a tag, because that's how HTML works. It then sees ? and goes "Error: this HTML is invalid HTML" and stops.
So the bottom line here is to read up on where and when PHP runs, vs where and when JS runs, but arguably even more importantly: never use document.write because it doesn't do what you think, at all.

Using javascript's return value as condition in a struts if tag

I am working on formatting HTML with struts2 and javascript, and am passing the return value of a function to a <s:if> tag. I would expect it to behave like any other conditional; however, the <s:if> tag consistently behaves as though it is returning false.
page.jsp
<s:if test="%{myFunction()}">
<p>foo</p>
</s:if>
<s:else>
<p>bar</p>
</s:else>
page.js
function myFunction() {
if(some_condition) { return true; }
else { return false; }
}
bar
I've tested the javascript function independently, and it's working as intended - both true and false are being returned depending on the conditions. The function is being properly included in the .jsp code (it's defined earlier in a <script> tag).
Intuitively, I believe I should be able to use the return value as a conditional, but I'm beginning to believe I might be incorrect. Documentation on this behavior is rather sparse, and the official struts2 documentation doesn't have much to say on whether it's possible or not.
Is this a syntax error, or have I run into a limit of struts2?
It is neither (1) a syntax error nor (2) a "limitation" of Struts 2.
If it was a syntax error you'd get... a syntax error, either on the server side in the logs, or on the client side in the JS console.
S2 is a standard action-based Java web framework; it knows nothing about anything on the client side: there is no (direct) interop between what happens on the server and what happens on the client (e.g., browser).
TL;DR: JSP pages run on the server. JavaScript runs on the client. There's no direct connection.
Pages sent to the client are rendered before being sent, before any JavaScript is run, etc. The server side knows nothing about the JavaScript on your page. (That's why you can render S2 tags into JS that the code then uses once it's on the client.)
If you want to be able to dynamically render DOM elements then everything has to be handled on the JS side, although your JS code can include S2 tags.
This is basic Java web app stuff: JSP files are just templates. They are completely rendered before being sent to the client as the response.

What happens when PHP is inlined in html (or other web files)?

I'm new to web development. I've google'd the question and found no result. To begin, consider the following code:
<p id="par">Hello World</p>
If you have PHP set-up, the following is valid:
<p id="par"><?php echo "Hello World";?></p>
Both produces the same result, but what I recall is that PHP codes are executed in the server, thus the following question arise concerning the execution of the code:
Is <p></p> element first retrieved from server, while some background ajax process waits for the "Hello World"?
I'd really like to know so I can make a more predictable code. Another possible scenario that bothers me is when using javascript and/or jQuery:
$(document).load(function(){
$("#foo").width($("#par").width());
});
which raises the question, does it wait for PHP server requests to finnish or does it just load the page therefore, some code that will need to react to the size of the <p> element above will be a bug?
Again, pardon the beginner question.
PHP it is server side program language. All code will be processed on server before return to client.
I believe in your case JavaScript is client side part. So.
PHP will generate HTML first. Then Browser load HTML(already with "Hello World") and Javascript. And in the end Javascript will get access to #foo DOM element.
But here can be case when Javascript loaded before HTML. In this case
$("#foo").width($("#par").width()) will do nothing or throw error because no #par element exist yet. To fix this you have to ensure that Javascript start work after all HTML loaded. For this you can use:
$(document).load(function() {
$("#foo").width($("#par").width())
});
I hope this will help you.
Ok all the time that you type a url in the browser bar and you press enter, your browser is generating a request http to a server.
So eg:
www.example.com/ -> is asking to the example.com server the page index.html which is just text.
When you have something like:
www.example.com/test.php -> again is just converting all the php in text and returning that text.
You can see this on your Network tab in Firebug for eg.
So PHP is just generating the html code for you straight forward linearly.
So about your question:
No it won't be bugged. If you analyse the html code you receive from both you cases, you'll see they are identicall.

How do I use javascript variable in LuCI Lua markup?

I am creating an HTML file for use with OpenWrt LuCI web interface. As discussed here: http://luci.subsignal.org/trac/wiki/Documentation/Templates I am using the Lua Markup language to run a Lua function called runDiag and I need to pass the javascript variable option to the runDiag function. I can't figure out how to make this work. I have tried various modifications to the markup inside the displayDiag function without success.
Can anyone help?
Example:
<%-
function runDiag(option)
return option
end
-%>
<script>
function displayDiag() {
var option = document.getElementById('iface').value;
document.getElementById('diag_text').innerHTML = '<%- write (runDiag(option)) -%>';
}
</script>
You can't do this. The Lua template is ran on the server, and the JavaScript code is ran on the client (i.e. web browser). They can't communicate.
The Lua code simply generates an HTML file to send to the client. It doesn't know about JavaScript; it's just some text that it's giving to the client. Here, option refers to a nonexistant Lua variable, which has the value of nil.
Conversely, the JavaScript code has no knowledge of the server-side Lua code. It just gets whatever the server generated. Thus, it only sees this line:
document.getElementById('diag_text').innerHTML = 'nil';
To communicate with the web server, you will need use AJAX or some other protocol.

How do I protect JavaScript files?

I know it's impossible to hide source code but, for example, if I have to link a JavaScript file from my CDN to a web page and I don't want the people to know the location and/or content of this script, is this possible?
For example, to link a script from a website, we use:
<script type="text/javascript" src="http://somedomain.example/scriptxyz.js">
</script>
Now, is possible to hide from the user where the script comes from, or hide the script content and still use it on a web page?
For example, by saving it in my private CDN that needs password to access files, would that work? If not, what would work to get what I want?
Good question with a simple answer: you can't!
JavaScript is a client-side programming language, therefore it works on the client's machine, so you can't actually hide anything from the client.
Obfuscating your code is a good solution, but it's not enough, because, although it is hard, someone could decipher your code and "steal" your script.
There are a few ways of making your code hard to be stolen, but as I said nothing is bullet-proof.
Off the top of my head, one idea is to restrict access to your external js files from outside the page you embed your code in. In that case, if you have
<script type="text/javascript" src="myJs.js"></script>
and someone tries to access the myJs.js file in browser, he shouldn't be granted any access to the script source.
For example, if your page is written in PHP, you can include the script via the include function and let the script decide if it's safe" to return it's source.
In this example, you'll need the external "js" (written in PHP) file myJs.php:
<?php
$URL = $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
if ($URL != "my-domain.example/my-page.php")
die("/\*sry, no acces rights\*/");
?>
// your obfuscated script goes here
that would be included in your main page my-page.php:
<script type="text/javascript">
<?php include "myJs.php"; ?>;
</script>
This way, only the browser could see the js file contents.
Another interesting idea is that at the end of your script, you delete the contents of your dom script element, so that after the browser evaluates your code, the code disappears:
<script id="erasable" type="text/javascript">
//your code goes here
document.getElementById('erasable').innerHTML = "";
</script>
These are all just simple hacks that cannot, and I can't stress this enough: cannot, fully protect your js code, but they can sure piss off someone who is trying to "steal" your code.
Update:
I recently came across a very interesting article written by Patrick Weid on how to hide your js code, and he reveals a different approach: you can encode your source code into an image! Sure, that's not bullet proof either, but it's another fence that you could build around your code.
The idea behind this approach is that most browsers can use the canvas element to do pixel manipulation on images. And since the canvas pixel is represented by 4 values (rgba), each pixel can have a value in the range of 0-255. That means that you can store a character (actual it's ascii code) in every pixel. The rest of the encoding/decoding is trivial.
The only thing you can do is obfuscate your code to make it more difficult to read. No matter what you do, if you want the javascript to execute in their browser they'll have to have the code.
Just off the top of my head, you could do something like this (if you can create server-side scripts, which it sounds like you can):
Instead of loading the script like normal, send an AJAX request to a PHP page (it could be anything; I just use it myself). Have the PHP locate the file (maybe on a non-public part of the server), open it with file_get_contents, and return (read: echo) the contents as a string.
When this string returns to the JavaScript, have it create a new script tag, populate its innerHTML with the code you just received, and attach the tag to the page. (You might have trouble with this; innerHTML may not be what you need, but you can experiment.)
If you do this a lot, you might even want to set up a PHP page that accepts a GET variable with the script's name, so that you can dynamically grab different scripts using the same PHP. (Maybe you could use POST instead, to make it just a little harder for other people to see what you're doing. I don't know.)
EDIT: I thought you were only trying to hide the location of the script. This obviously wouldn't help much if you're trying to hide the script itself.
Google Closure Compiler, YUI compressor, Minify, /Packer/... etc, are options for compressing/obfuscating your JS codes. But none of them can help you from hiding your code from the users.
Anyone with decent knowledge can easily decode/de-obfuscate your code using tools like JS Beautifier. You name it.
So the answer is, you can always make your code harder to read/decode, but for sure there is no way to hide.
Forget it, this is not doable.
No matter what you try it will not work. All a user needs to do to discover your code and it's location is to look in the net tab in firebug or use fiddler to see what requests are being made.
From my knowledge, this is not possible.
Your browser has to have access to JS files to be able to execute them. If the browser has access, then browser's user also has access.
If you password protect your JS files, then the browser won't be able to access them, defeating the purpose of having JS in the first place.
I think the only way is to put required data on the server and allow only logged-in user to access the data as required (you can also make some calculations server side). This wont protect your javascript code but make it unoperatable without the server side code
I agree with everyone else here: With JS on the client, the cat is out of the bag and there is nothing completely foolproof that can be done.
Having said that; in some cases I do this to put some hurdles in the way of those who want to take a look at the code. This is how the algorithm works (roughly)
The server creates 3 hashed and salted values. One for the current timestamp, and the other two for each of the next 2 seconds. These values are sent over to the client via Ajax to the client as a comma delimited string; from my PHP module. In some cases, I think you can hard-bake these values into a script section of HTML when the page is formed, and delete that script tag once the use of the hashes is over The server is CORS protected and does all the usual SERVER_NAME etc check (which is not much of a protection but at least provides some modicum of resistance to script kiddies).
Also it would be nice, if the the server checks if there was indeed an authenticated user's client doing this
The client then sends the same 3 hashed values back to the server thru an ajax call to fetch the actual JS that I need. The server checks the hashes against the current time stamp there... The three values ensure that the data is being sent within the 3 second window to account for latency between the browser and the server
The server needs to be convinced that one of the hashes is
matched correctly; and if so it would send over the crucial JS back
to the client. This is a simple, crude "One time use Password"
without the need for any database at the back end.
This means, that any hacker has only the 3 second window period since the generation of the first set of hashes to get to the actual JS code.
The entire client code can be inside an IIFE function so some of the variables inside the client are even more harder to read from the Inspector console
This is not any deep solution: A determined hacker can register, get an account and then ask the server to generate the first three hashes; by doing tricks to go around Ajax and CORS; and then make the client perform the second call to get to the actual code -- but it is a reasonable amount of work.
Moreover, if the Salt used by the server is based on the login credentials; the server may be able to detect who is that user who tried to retreive the sensitive JS (The server needs to do some more additional work regarding the behaviour of the user AFTER the sensitive JS was retreived, and block the person if the person, say for example, did not do some other activity which was expected)
An old, crude version of this was done for a hackathon here: http://planwithin.com/demo/tadr.html That wil not work in case the server detects too much latency, and it goes beyond the 3 second window period
As I said in the comment I left on gion_13 answer before (please read), you really can't. Not with javascript.
If you don't want the code to be available client-side (= stealable without great efforts),
my suggestion would be to make use of PHP (ASP,Python,Perl,Ruby,JSP + Java-Servlets) that is processed server-side and only the results of the computation/code execution are served to the user. Or, if you prefer, even Flash or a Java-Applet that let client-side computation/code execution but are compiled and thus harder to reverse-engine (not impossible thus).
Just my 2 cents.
You can also set up a mime type for application/JavaScript to run as PHP, .NET, Java, or whatever language you're using. I've done this for dynamic CSS files in the past.
I know that this is the wrong time to be answering this question but i just thought of something
i know it might be stressful but atleast it might still work
Now the trick is to create a lot of server side encoding scripts, they have to be decodable(for example a script that replaces all vowels with numbers and add the letter 'a' to every consonant so that the word 'bat' becomes ba1ta) then create a script that will randomize between the encoding scripts and create a cookie with the name of the encoding script being used (quick tip: try not to use the actual name of the encoding script for the cookie for example if our cookie is name 'encoding_script_being_used' and the randomizing script chooses an encoding script named MD10 try not to use MD10 as the value of the cookie but 'encoding_script4567656' just to prevent guessing) then after the cookie has been created another script will check for the cookie named 'encoding_script_being_used' and get the value, then it will determine what encoding script is being used.
Now the reason for randomizing between the encoding scripts was that the server side language will randomize which script to use to decode your javascript.js and then create a session or cookie to know which encoding scripts was used
then the server side language will also encode your javascript .js and put it as a cookie
so now let me summarize with an example
PHP randomizes between a list of encoding scripts and encrypts javascript.js then it create a cookie telling the client side language which encoding script was used then client side language decodes the javascript.js cookie(which is obviously encoded)
so people can't steal your code
but i would not advise this because
it is a long process
It is too stressful
use nwjs i think helpful it can compile to bin then you can use it to make win,mac and linux application
This method partially works if you do not want to expose the most sensible part of your algorithm.
Create WebAssembly modules (.wasm), import them, and expose only your JS, etc... workflow. In this way the algorithm is protected since it is extremely difficult to revert assembly code into a more human readable format.
After having produced the wasm module and imported correclty, you can use your code as you normallt do:
<body id="wasm-example">
<script type="module">
import init from "./pkg/glue_code.js";
init().then(() => {
console.log("WASM Loaded");
});
</script>
</body>

Categories

Resources