I realized a javascript parser built in a web page.
A user can put a javascript code in the text-area like:
var i = 0;
i++;
var y = i * 10;
document.write(y);
that is parsed in order to generate some outputs (e.g., document.write stream, and so on).
The function parse is called when textarea change event is generated.
function parse(text) {
try {
....
eval(text);
} catch (e) {
....
return {
status : false, output : ..., ... : ...
};
}
return {
status : true, output : ...., ... : ...
};
}
Everything works well but I have problem when a user writes a loop in the text area (e.g., for(var i=0; i<10; ), while(true))
because the application goes in loop.
To avoid this problem, I would ask you all some questions/solutions for this problem:
Are there some javascript libraries or functions that allow to
eval a javascript code but are loop-free?
Can I ask to execute my parse function but in a fixed time? After such time I would generate an exception that stops the eval function.
Before to call the eval(text) I can call a checkIfThereAreLoops function that analyses the text seeking for patterns like for(var i=0; i<10; ) or while(true). Is this a good solution? Can I use a regular expression to seek these patterns?
If you are trying to see whether arbitrary code will terminate, you will be in for a rough time the Halting Problem is NP-Hard.
So you are right to think that you would either need a preventative measure on your parse function that either times out or dismisses unsafe input.
I'm not aware of a way to interrupt eval without the browser imposing a 'this script is running too long' limit, so you would want to sanitize the input and not evaluate anything with a loop: This will be tricky since you can't just search for constructs such as for, while etc and avoid recursive function calls.
This is a difficult problem to solve...
One 'hacky' solution could be to insert a unique variable declaration into the top of the entered code (hidden of course) and to increment this variable every other line from within the input code (again, hide these insertions and allow for syntax constructs becoming broken. Also insert sanity checks at each increment if unique_var > 99999 exit; (where 99999 is some limit you impose).
This should at least stop infinite loops.
Related
Does anyone know of a way to eval a string so that if it (or a function it defines) generates an error, the line and column numbers shown in the stack trace will be offset by an amount specified in advance?
Alternatively, suppose I want to break up a long source string into chunks and evaluate them separately, but still get stack traces that look as though the entire string was evaluated in one go. Is there any way to achieve this effect, except for using empty lines and columns? (I need a browser-based solution, preferably cross-browser, but I can settle for something that works on at least one of the major browsers.)
I don't think is it possible because the underlying mechanism that is assumed working is actually deprecated. For security reasons browsers don't pass the error object to Javascript anymore.
However, since you are working with a custom programming language that gets compiled into Javascript, you know what the structure of the resulting script will be. You could also introduce statement counters in the resulting Javascript, so you can always know what the last thing executed was. Something like:
function(1); function(2);
function(3);
could be translated as:
var __column=0;
var __line=0;
function(1); __column+=12;
function(2); /*__column+=12;*/ __line++; __column=0;
function(3); /*__column+=12;*/ __line++; __column=0;
Where 12 is "function(n);".length.Of course, the resulting code is ugly, but you could enable this behaviour with a debug flag or something.
The best solution I've found so far is to prepend a sourceURL directive to each string before it's eval'ed, giving it a marker in the form of a unique file name in the stack trace. Stack traces are then parsed (using the parser component stacktracejs) and corrected by looking up the line offsets associated with the markers.
var evalCounter = 0;
var lineCounter = 0;
var lineOffsetTable = {};
function myEval(code) {
lineOffsetTable[evalCounter] = lineCounter;
lineCounter += countLines(code);
return eval("//# sourceURL=" + (evalCounter++) + "\n" + code);
}
window.onerror = function(errorMsg, url, lineNumber, column, e) {
var stackFrames = ErrorStackParser.parse(e);
logStackTrace(stackFrames.map(function(f) {
if(f.fileName in lineOffsetTable)
f.lineNumber += lineOffsetTable[f.fileName];
return f;
}));
};
Unfortunately, this only works in Firefox at the moment. Chrome refuses to pass the error object to the onerror callback (a problem which only happens with eval'ed code, strangely enough) and IE ignores the sourceURL directive.
I have a Jquery function in MVC View that check if at least one checkbox is clicked. Function is working properly if I use hardcoded string. But when I add
#Resources.myString into, it stops working, I can't figure out why
$('.form-horizontal').on('submit', function (e) {
if ($("input[type=checkbox]:checked").length === 0) {
e.preventDefault();
alert("This is working");
alert(#Resources.myString); //with this the function is not working anymore
return false;
}
});
I need to add the the string for multilingual purpose.
I tried diferent aproches
alert(#Resources.myString);
alert(#Html.Raw(Resources.myString))
var aaa = { #Html.Raw(Resources.myString)} //and calling the aaa
I think I am missing some basic knowlage of how this should work together
During page rendering, #Resources.myString will be injected as is in the code. For instance, if myString == "abc";, you'll end up with alert(abc); which is not what you want.
Just try to enclose your string in quotes:
alert("#Resources.myString");
As an aside, putting Razor code in Javascript logic is usually considered bad practice, as it prevents you from putting Javascript code in separate files (and therefore caching), and makes the code less readable.
Take a look as this question and the provided answer which gives a simple way to deal with that.
As ASP.NET dynamically generates HTML, CSS, JS code, the best way to find the error is to read the generated sources (Ctrl + U in most modern browsers).
You will see that your code
alert(#Resources.myString);
produces
alert(yourStringContent);
and should result in a console error yourStringContent is not defined.
You need to use quotes as you are working with a JavaScript string:
alert('#Resources.myString');
It will produce a correct JavaScript code like:
alert('yourStringContent');
I'm new to programming so this question may be really basic but I need some help.
I have a code for generating a message a certain no. of times from input given by the user.
(ex.)
var count=document.getElementById("count").value;
for(var i=0;i<count;i++)
{
GenerateMessage();
}
function GenerateMessage()
{
\*
...*/
}
But no what matter the value of count is the function is executed only once. Am I doing something wrong?
EDIT: Works fine with breakpoints. But during program execution program generates one message irrespective of count value goven by user
It should be
document.getElementById("count").value
Value is a property, not a function.
try this //jsfiddle.net/W4Km8/286/ its useful for you
I have created a little robot like the Karel robot (Wikipedia) which is based on javascript.
Karel4Web
The robot can be controlled with some simple commands such as "forward", "turnright" and so on.
The user can write a javascript program to control the robot which then goes through javascripts "eval()" function so that the robot moves.
The problem is that I want the robot to move slowly so that you can see what he is doing and so that you can highlight the current code line in the editor.
Current method: Parsing
At the moment I have solved this (in the offline version) by parsing each line in the textarea and then building a stack of action which are then executed one after another with window.setTimeout. But this is of course limited because I have to write parsing code for every little javascript language contruct which is much work and error prone.
Some additional information to this:
Parsing version: http://abi-physik.de/_niki2/niki.php
Parsing version js code: http://abi-physik.de/_niki2/js/niki.js
Important functions are at the bottom of the script: run(), execute()
I am currently parsing the user script line by line and adding the actions to a stack. If the parser encounters an "if" it will begin a new stack and add all actions to that stack. if the parser then encounters an "}" it will close the "if" stack and continue to add actions to the base stack.
Any idea to improve this?
I would say have those functions register to some queue instead of having them execute the JavaScript directly.
var moveQueue = [];
function forward(){
moveQueue.push(_forward);
}
function _forward(){
alert("move forward");
}
function backward(){
moveQueue.push(_backward);
}
function _backward(){
alert("move backward");
}
Than when it runs you would use a setTimeout and
function run(){
var curStep = 0;
function go(){
moveQueue[curStep]();
curStep++;
if(curStep<moveQueue.length){
window.setTimeout(go,500);
}
}
}
You still would need to parse it out to figure out the if statement logic, but this is one of many ways that will allow you to control the speed of execution.
Javascript doesn't have a sleep() function, so yes, using setTimeout or setInterval is the way to go.
You could parse the 'instructions' first, assemble an array of actions that need to be carried out, then use setInterval to arrange for a function to be regularly called which takes the next instruction and carries it out (or clears the interval, if there are no more instructions waiting to be processed).
I am writing a greasemonkey script. Recently i had this same problem twice and i have no idea why is this happening.
function colli(){
.....
var oPriorityMass = bynID('massadderPriority');//my own document.getElementById() function
var aPriorities = [];
if (oPriorityMass) {
for (var cEntry=0; cEntry < oPriorityMass.childNodes.length; cEntry++) {
var sCollNumber = oPriorityMass.childNodes[cEntry].getAttribute('coll');
if (bynID('adder' + sCollNumber + '_check').checked)
aPriorities.push(parseInt(sCollNumber));
}
}
.....
}
So the mystery of this is, one day i had oPriorityMass named as oPririoty. It was working fine, but the whole function was not yet complete and i started working on another functions for my script. These functions have no connection with each other.
Few days later i decided to go back to my function in the above example and finish it. I ran a test on it without modifying anything and got an error in the firefox's (4) javascript error console saying that oPriority.chilNodes[cEntry] is undefined. NOTE, few days back i have tested it exactly the same way and there was no such problem at all.
Ok, so, i decided to rename oPriority to oPriorityMass. Magically, problem got solved.
At first i thought, maybe there was some conflict of 2 objects, with the same name being used in different functions, which somehow continued to live even outside of function scope. My script is currently over 6000 lines big, but i did a search and found out that oPriority was not mentioned anywhere else but in this exact function.
Can somebody tell me, how and why is this happening? I mentioned same thing happened twice now and they happened in different functions, but the same problem node.childNodes[c] is undefined yet node is not null and node.childNodes.length show correct child count.
What is going on? How do i avoid such problems?
Thank you
EDIT: The error given by error console is
Error: uncaught exception: TypeError: oPriorityMass.childNodes[cEntry] is undefined
In response to Brocks comment:
GM_log(oPriorityMass.childNodes[cEntry]) returns undefined as a message. So node.childNodes[c] is the thing that is undefined in general.
My script creates a div window. Later, the above function uses elements in this div. Elements do have unique IDs and i am 100% sure the original site don't know about them.
My script has a start/stop button to run one or the other function when i need to.
I have been refreshing the page and running my script function now. I have noticed that sometimes (but not always) script will fail with the described error on the first run, however, if i run it again (without refreshing the page) it starts working.
The page has a javascript that modifies it. It changes some of it's element widths so it changes when the browser is resized. But i know it has no effect on my div as it is left unchanged when i resize browser.
EDIT2:
function bynID(sID) {
return top.document.getElementById(ns(sID));
}
function ns(sText) {
return g_sScriptName + '_' + sText;
}
ns function just adds the script name in front of the ID. I use it when creating HTML element so my elements never have the same id as the web page. So bynID() is simple function that saves some typing time when i need to get element by ID.
I have modified my colli() function to include check
if (oPriorityMass) {
if (!oPriorityMass.childNodes[0]) {
GM_log('Retrying');
setTimeout(loadPage,2000);
return;
}
for (var cEntry=0; cEntry < oPriorityMass.childNodes.length; cEntry++) {
var sCollNumber = oPriorityMass.childNodes[cEntry].getAttribute('coll');
if (bynID('adder' + sCollNumber + '_check').checked)
aPriorities.push(parseInt(sCollNumber));
}
}
The loadPage function does 1 AJAX call, then i run few XPATH queries on it, but the actual contents are never appended/shown on the page, just kept inside document.createElement('div'), then this function calls colli(). So now, as i have modified my function, i checked the error console and saw that it may take up to 5 tries for it to start working correctly. 5 x 2seconds, thats 10 seconds. It is never 5 retries always, may vary There's got to be something else going on?
In Firefox, childNodes can include #text nodes. You should check to make sure that childNodes[cEntry] has nodeType == 1 or has a getAttribute method before trying to call it. e.g.
<div id="d0">
</div>
<div id="d1"></div>
In the above in Firefox and similar browsers (i.e. based on Gecko and WebKit based browsers like Safari), d0 has one child node, a text node, and d1 has no child nodes.
So I would do something like:
var sCollNumber, el0, el1;
if (oPriorityMass) {
for (var cEntry=0; cEntry < oPriorityMass.childNodes.length; cEntry++) {
el0 = oPriorityMass.childNodes[cEntry];
// Make sure have an HTMLElement that will
// have a getAttribute method
if (el0.nodeType == 1) {
sCollNumber = el0.getAttribute('coll');
el1 = bynID('adder' + sCollNumber + '_check');
// Make sure el1 is not falsey before attempting to
// access properties
if (el1 && el1.checked)
// Never call parseInt on strings without a radix
// Or use some other method to convert to Number
aPriorities.push(parseInt(sCollNumber, 10));
}
}
Given that sCollNumber seems like it is a string integer (just guessing but it seems likely), you can also use:
Number(sCollNumber)
or
+sCollNumber
whichever suits and is more maintainable.
So, according to your last edit, it now works, with the delay, right?
But when I suggested the delay it was not meant to do (even more?) ajax calls while waiting!!
NOT:
if (!oPriorityMass.childNodes[0]) {
GM_log('Retrying');
setTimeout(loadPage,2000);
return;
More like:
setTimeout (colli, 2000);
So the ajax and the other stuff that loadPage does could explain the excessive delay.
The random behavior could be caused by:
return top.document.getElementById(ns(sID));
This will cause erratic behavior if any frames or iframes are present, and you do not block operation on frames. (If you do block such operation then top is redundant and unnecessary.)
GM does not operate correctly in such cases -- depending on what the script does -- often seeming to "switch" from top scope to frame scope or vice versa.
So, it's probably best to change that to:
return document.getElementById (ns (sID) );
And make sure you have:
if (window.top != window.self) //-- Don't run on frames or iframes
return;
as the top lines of code.
Beyond that, it's near impossible to see the problem, because of insufficient information.
Either boil the problem into a Complete, Self Contained, Recipe for duplicating the failure.
OR, post or link to the Complete, Unedited, Script.