Javascript ILLEGAL char message when eval'ing text using new Function - javascript

We have a badge script that pulls a json config file and then loads external scripts asynchronously and executes code when they're loaded. The js is stored as a string in the JSON file. To avoid using eval() we're executing the code as follows:
var codeFromJSON = "alert('this far')";
var func = new Function(codeFromJSON);
func();
This works, but returns the following error in chrome, and similar errors in other browsers:
Uncaught SyntaxError: Unexpected token ILLEGAL
At first I thought this had to do with something simple—copying the snippet from the web, etc.—but I've retyped and retested, and still get the same thing...
Any ideas?

Related

Why does the code work within <script> tag, but not in external .js file? 🤨

I tested out this code within a <script> tag, and then in an external .js file linked to the .html file. The former works; the latter doesn't. Why?
<script>
const x = document.createElement('div');
x.innerHTML = "<%=JSON.stringify(result)%>";
console.log(JSON.parse(x.childNodes[0].nodeValue));
</script>
The same code placed in an external linked file gives me this error message:
VM125:1 Uncaught SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at my.js:3
(anonymous) # my.js:3
Why?
As charlietfl points out, <%=JSON.stringify(result)%> is an ejs statement that never gets compiled.
const x = document.createElement('div');
x.innerHTML = "<%=JSON.stringify(result)%>";
The above code creates the following HTML:
<div><%=JSON.stringify(result)%></div>
If this were in an .ejs file, it would be replaced with something like:
<div>"foo"</div>
Depending on what JSON.stringify(result) evaluates to (assuming result equals 'foo' here).
This is a shot in the dark, but what you probably want to do is have something like this in your .ejs file:
window.result = <%=JSON.stringify(result)%>;
Then replace the corresponding line of your current code with:
x.innerHTML = result;
Basically remove the .ejs syntax <%= and %>.

xml2json.js error: Syntax error

I want to convert an XML file, after many trials with my AngularJS application, I've simply uploaded on the server the samples.html that I've found at https://github.com/abdmob/x2js .
The result is always the same: on the console I receive a "SCRIPTxxxx: Syntax error xml2json.min.js" and "SCRIPTxxxx: 'X2JS' is undefined". The script is linked normally, like:<script type="text/javascript" src="/vendor-scripts/xml2json.min.js"></script> (same issue with xml2json.js) and also this simple code gives the same error: var x2js = new X2JS();
var xmlText = "<MyRoot><test>Success</test><test2><item>val1</item><item>val2</item></test2></MyRoot>";
var jsonObj = x2js.xml_str2json( xmlText );. Does anyone know if this is a known issue (I didn't find anything on the net) or if there are other libraries to do this job?

External JavaScript file is not defined

For a web project, I've included a JavaScript file as a script src, as shown here.
<script src="xml2json.js"> //same directory as the web project
Next, I tried to invoke a method within xml2json, called xml_str2json.
downloadUrl("ship_track_ajax.php", function(data) {
var xml_string = data.responseText; //an XML string
//A parser to transform XML string into a JSON object is required.
//Use convert XML to JSON with xml2json.js
var markers = xml2json.xml_str2json(xml_string);
}
However, console log indicates "Uncaught ReferenceError: xml2json is not defined", even though xml2json is included as a script src. Can anyone tell me as to what is wrong?
You have to call the function directly in javascript without reffering the filename as like
xml_str2json(xml_string);
If the function is defined in any of the included file it will be invoked.
I hope this will solve your problem
Maybe you should try this:
var json = xml2json(parseXml(xml), " ");
See Demo from https://github.com/henrikingo/xml2json

Loading and reading XML files in cocos2d-x 3.0 javascript scripts

How should one proceed to load XML content from a javascript script in cocos2d-x 3.0?
I need to parse an XML file but DOMParser is unavailable:
var text="<note>";
text=text+"<content>whatever blablabla</content>";
text=text+"</note>";
var parser=new DOMParser();
var doc=parser.parseFromString(text,'text/xml');
results in ReferenceError: DOMParser is not defined.
How should I proceed to load and manipulate the XML?
Even this solution fails:
var doc = document.implementation.createDocument("");
ReferenceError: document is not defined.
From the V2.2.1 documentation I tried the SAXParser to no avail:
cc.SAXParser.getInstance().parse(fullPath);
TypeError: cc.SAXParser is undefined
To paliate to the removal of cc.SAXParser in cocos2d-x 3.0 the solution is to use a pure javascript parser until a better solution is made available.

With gjs, how can I write Soup.Buffer chunks of data to a file?

I'm writing a GTK javascript program that downloads a file and writes it to disk. Here's what my code looks like:
const Gio = imports.gi.Gio;
const Soup = imports.gi.Soup;
// start an http session to make http requests
let _httpSession = new Soup.SessionAsync();
Soup.Session.prototype.add_feature.call(_httpSession, new Soup.ProxyResolverDefault());
// open the file
let file = Gio.file_new_for_path(path);
let fstream = file.replace(null, false, Gio.FileCreateFlags.NONE, null);
// start the download
let request = Soup.Message.new('GET', url);
request.connect('got_chunk', Lang.bind(this, function(message, chunk){
// write each chunk to file
fstream.write(chunk, chunk.length, null);
}));
this._httpSession.queue_message(request, function(_httpSession, message) {
// close the file
fstream.close(null);
});
I get an error on the fstream.write() line:
JS ERROR: !!! Exception was: Error: Unhandled GType GCancellable unpacking GArgument from Number
JS ERROR: !!! message = '"Unhandled GType GCancellable unpacking GArgument from Number"'
JS ERROR: !!! fileName = '"./torbrowser-launcher"'
JS ERROR: !!! lineNumber = '402'
JS ERROR: !!! stack = '"([object _private_Soup_Message],[object _private_Soup_Buffer])#./torbrowser-launcher:402
("2.3.25-2")#./torbrowser-launcher:122
wrapper("2.3.25-2")#/usr/share/gjs-1.0/lang.js:204
("2.3.25-2")#/usr/share/gjs-1.0/lang.js:145
("2.3.25-2")#/usr/share/gjs-1.0/lang.js:239
#./torbrowser-launcher:489
"'
The only reference to this error that I can find is in this thread: https://mail.gnome.org/archives/gnome-shell-list/2012-July/msg00126.html
That person ended up giving up and porting his code to python.
I'm also confused by what the 'got_chunk' callback passes. The chunk field is a Soup.Buffer (http://www.roojs.com/seed/gir-1.2-gtk-3.0/gjs/Soup.Buffer.html). I can get its length with chunk.length, but when I try printing chunk.data it's undefined. When I just print chunk it prints: [object _private_Soup_Buffer].
fstream is a Gio.FileOutputStream (http://www.roojs.com/seed/gir-1.2-gtk-3.0/gjs/Gio.FileOutputStream.html). The write method is: write(String buffer, guint32 count, Cancellable cancellable), and cancellable is optional. Weirdly enough, if I replace the write line with this I still get the exact same error:
fstream.write('test ', 5, null);
I was hitting exactly the same problem. After a lot of trial and error, it boiled down to two issues with the write() call:
It seems that the documentation of the write function you are using (http://www.roojs.com/seed/gir-1.2-gtk-3.0/gjs/Gio.FileOutputStream.html) is wrong; the write method signature is (as far as I can tell):
write(String buffer, Cancellable cancellable, guint32 count)
Yet if you just use fstream.write(chunk, null, chunk.length); you will write a file full of zeros. I don't know why (something to do with the way GJS binds to the underlying C library) but you should use chunk.get_data() instead of just chunk. I.e. replace the write call in your code with:
fstream.write(chunk.get_data(), null, chunk.length);

Categories

Resources