Executing Javascript from inside textarea (custom JS console) - javascript

I am interested in building a text editor in a CMS backend that allows users to write Javascript into a textarea and test it while editing.
The closest I can think of is something like.
document.head.appendChild(document.createElement('script')).src='http://site.com/file.js';
But instead of
.src='http://site.com/file.js';
I would need to fill the script element with the textarea value. Does anyone have any idea as how to handle something like this?

I have written a simple one of these myself (doesn't work in IE) here: http://phrogz.net/tmp/simplejs.html

Use the eval() function.
eval(document.getElementById('wmd-input').value);
And if you're going to let users enter JavaScript into your CMS, be sure you're up to speed on cross-site scripting (XSS).

I think you should make an ajax call to load the page. I'd recommend JQuery, which makes it very easy, and there are plenty of examples on their site.
It would look something like this:
$.get('http://site.com/file.j', function(data) {
$('#txta').text(data);
});
Where 'txta' is the id of the textarea.
If you want to execute the script in the browser, you can use the javascript eval() function - but I would exercise extreme caution with this approach since it can lead to all sorts of security flaws, including cross-site scripting attacks.

Related

How to secure javascript code from being run on other domain (stolen) ? need more ideas

First, this could look like duplicate for
How to prevent your JavaScript code from being stolen, copied, and viewed ?
And other, but it's not.
I search for ideas that can do, that stealing of JS can be very hard
Some of my examples:
of course obfuscate code
use a document.location an check if some
letter in domain equals to letter on that position where script
normally works
use part of this location in function call, something like eval('first_part_of_function_name'+part_from_location+'third_pard(parameters)');
store some important constant need in application in some element in your page-design, and get it from there in JS like $('#header div.onright a rel')
get some portion of script by AJAX and eval() it
add to script some unnecessary function, instructions.
check for existance of some elements in page (copyright text on footer)
generate some time-variable hash in PHP and put in JS, where will be function that checks this hash and current time to work or not
maybe use of other JS files ? or events binded to elements hidden in very common scripts (like bind some action in jquery-min.X.X.X.js file where all jquery is.
Are they good ideas ? Have some more ? I think that most important can be variety of things wich you can do with document location, is that the only element that will be driffrent than working in normal coditions on our site ?
No matter how complex you make your code, it can always be read, if necessary with abstract interpretation, i.e. automatically capturing the essence of your code. Code without knowledge of internals, variable names (I assume you're already using minimization, for example with the YUI compressor), documentation, support, and generalization is worthless for anyone else.
If a competitor (or potential customers) of yours is stealing your code, consider simply suing them. If it's some random guy on the internet, why do you care?
One more tool http://closure-compiler.appspot.com/home

Prevent site from showing content based on certain date

The site www.refdag.nl shows its content based on what day it is: on sunday they don't want their readers to read articles because of religious reasons.
The Javascript which they use to accomplish this looks like this:
http://www.refdag.nl/js/common/sunday_block.js
So, changing the client's date is already a solution to work around this. Turning off all Javascript is also possible. But it would be nicer if I could just leave just the part of the script mentioned above out on the client.
What is a good solution for it? Blocking the above mentioned file does not work, because the site uses a single giant javascript file where files like these are appended to each other (http://www.refdag.nl/js/www.refdag.nl-bundle.js?rev=3994). Are there any plugins for Chrome in which you can rewrite javascript before it gets loaded or something?
This is not what AdBlock is made for, but I believe you should be able to tell it to block the script.
Not much to do other than disable script or read the page in an HTA or so. The script is inline and in an anonymous function so it is not possible to intercept the script unless you are able to rewrite the date function before the script is executed, like
javascript:void(Date=function() { return null })
or similar
I would personally use
view-source:http://www.refdag.nl/
and paste it into an IDE after adding
<base ref="http://www.refdag.nl/" /> and maybe my script or delete the script

Is there a way to validate the HTML of a page after AJAX operations are performed on it?

I'm writing a web app that inserts and modifies HTML elements via AJAX using JQuery. It works very nicely, but I want to be sure everything is ok under the bonnet. When I inspect the source of the page in IE or Chrome it shows me the original document markup, not what has changed since my AJAX calls.
I love using the WC3 validator to check my markup as it occasionally reminds me that I've forgotten to close a tag etc. How can I use this to check the markup of my page after the original source served from the server has been changed via Javascript?
Thank you.
Use developer tool in chrome to explore the DOM : it will show you all the HTML you've added in javascript.
You can now copy it and paste it in any validator you want.
Or instead of inserting code in JQuery, give it to the console, the browser will then not be able to close tags for you.
console.log(myHTML)
Both previous answers make good points about the fact the browser will 'fix' some of the html you insert into the DOM.
Back to your question, you could add the following to a bookmark in your browser. It will write out the contents of the DOM to a new window, copy and paste it into a validator.
javascript:window.open("").document.open("text/plain", "").write(document.documentElement.outerHTML);
If you're just concerned about well-formedness (missing closing tags and such), you probably just want to check the structure of the chunks AJAX is inserting. (Once it's part of the DOM, it's going to be well-formed... just not necessarily the structure you intended.) The simplest way to do that would probably be to attempt to parse it using an XML library. (one with an HTML mode that can be made strict, if you're not using XHTML)
Actual validation (Testing the "You can't put tag X inside tag Y" rules which browsers generally don't care too much about) is a lot trickier and, depending on how much effort you're willing to put into it, may not be worth the trouble. (Because, if you validate them in isolation, you'll get a lot of "This is just a fragment" false positives)
Whichever you decide to use, you need to grab the AJAX responses before the browser parses them if you want a reliable test result. (While they're still just a string of text rather than a DOM tree)

Is it a bad idea to auto generate javascript code from the server?

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.

How do I know if Javascript has been turned off inside browser?

I assume that you can't use a JavaScript code snippet to validate if the browser user has turned off JavaScript. So what can I use instead? Can someone offer a code sample?
I'm looking to wrap an if/then statement around it.
I often code in CFML, if that helps.
this is a total hack but you could use an iframe inside the noscript tag to trigger an HTTP GET on a url to tell the server that a user doesn't have javascript enabled.
<body>
...
...
<noscript>
<iframe src ="/nojs.aspx?SOMEIDENTIFIER=XXXX&NOJS=TRUE" style="display: none;">
</iframe>
</noscript>
...
...
</body>
Use the <noscript> HTML tags.
Not sure what you are trying to do but if you just need to inform the user that Javascript is required you can just use the '<noscript>' tag. If you need to know on the server you could make an Ajax style request to the server from javascript. If you get the request javascript is working otherwise its not.
Are we talking about something like this:
JavaScript:
<body>
...
...
<script type="text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
<noscript>Your browser does not support JavaScript!</noscript>
...
...
</body>
He's asking for a check to see if javascript is enabled.
I can only think of doing exactly what the OP said - try using some Javascript with an interval to send a callback if JS is activated - unfortunately I don't think you can check server side whether JS is enabled which is why you use tags rather than render different content from the server.
If you use Unobtrusive JavaScript then you don't need to check whether the user has JavaScript enabled.
If they have got JavaScript enabled then they'll get the full effect, but if they haven't then users will still be able to use your site. And as well as being better for accessibility you might find this approach boosts your SEO.
<noscript>
...some non-js code
</noscript>
Yes that NoScript snippet is right.
You might have javascript execute some AJAX query and check to see if it has. Those that download the page and don't execute the query either have JS disabled or they're robots.
Really all you can do is put some message in the tags. I seem to remember trying this on ASP.NET somewhere, but you can really only tell if the browser supports Javascript, not whether or not it is actually allowed/enabled.
I don't know much about CFML, but .NET has the ability to detect browser capabilities. It does not, however, have the ability to detect if the browser is capable of javascript, but has it turned off. So, you're stuck there too.
Besides the HTML noscript tag, there's not much you can do, as far as I know, besides writing javascript progressively (see progressive enhancement) so that you don't need to check for Javascript:off.
I don't know JS, but would it be possible to modify the links inside the page with JS? If someone goes to the unmodified link, they're not using JS, but if they do then they are using JS. Does this make any sense?
Have never worked out how to do it without a round trip, so it depends on what your goal is.
If they have to have javascript to proceed, then I have (in .net) done things like disabling the login button at the server side, then enabled it client side it with javascript, and used a noscript tag to show an error message.
If it has to work either way, you can use progressive enhancement, and / or use js to set a hidden field and then set a session variable, but this means that you don't know until they get to the second request.
you could write
<script type="text/javascript" language="javascript">document.write("<input type='hidden' name='hasJs' value='1' />");
or otherwise write a cookie via js and then read it at the server if you want to check server side for js.
if you are looking for a way to check it server side, you're can send the user a js that puts a cookie.... if the cookie exist on a a request then you can tell if the scripted worked or not!
One reliable way to do this is using javascript's $.post to send a note to your server. (Apologies if there's any errors in this, written off top of my head, will update later when I get around to testing). Should allow you to build it so you can even pull from session data if they're using javascript, which will allow you to serve up replacements for javascript without having to resort to .
Your on-page script:
<script>
function myJavascriptTest(){
$.post ()('myJavascriptTest.php', {myJavascriptOn: true}, function(){
return true;
}
myJavascriptTest()
</script>
And in the targeted .php...
<?php
if ($_POST['myJavascriptOn'] == true){
$_SESSION['javascriptIsOn'] = true;
} else {
$_SESSION['javascriptIsOn'] = false;
}
?>

Categories