SyntaxError: Unexpected token '<' on valid javascript - javascript

I have what I believe is valid javascript. However I get this: SyntaxError: Unexpected token '<'. Removing any of the script blocks, or changing around the order in the 'a' string fixes the issue. Why is that?
<script>
let a = "<!-- <script>";
</script>
<script></script><!-- --><script></script>

You get the same error with:
<script>
document.write('<script>alert("foo")</script>');
</script>
When "parsing" the page the browser sees this as an attempt to nest a <script> block inside another one. e.g.
<script>
<script>alert("foo")</script>
</script>
The solution is to trick the browser to see something different:
<script>
document.write('<scr' + 'ipt>alert("foo")</scr' + 'ipt>');
</script>

It seems like opening a <script> tag will make interpreter wait for javascript code until the last </script> is found, except if there is a second <script> opened with javascript inside of it.
Simple <script></script> will be interpreted as part of the JS code, which is invalid.
Might be related to this thread.

Related

Trying to append html string fail with jQuery

I'm trying to append the following string to head with jQuery :
"<script type='text/javascript'> window['adrum-app-key'] = 'dummy';</script>"
But it always fails. Trying to do the same with 'Hello' string for example works as expected.
Following the code snippet I use to append the string :
var integrationScriptTag = handlebars.partials.integration(integrationData);
$(document).ready(function() {
$('head').append(integrationScriptTag.trim());
});
First string is the result of parsing integrationData.
Any help will really be appreciated.
Edit: I realize I misguided some of you with the first string. It is just a representation of what is produced by the first line of the second code snippet. So it doesn't really matter if it is some quote marks or not. The fact is I don't use a literal but rather a variable which is equal to the first string. I corrected the syntax so that there is no more confusion.
Here is the jsFiddle reproducing the problem.
jsFiddle
This should fix it:
'<script type=\'text/javascript\'> window[\'adrum-app-key\'] = \'dummy\';</script>'
or this would too:
'<script type="text/javascript"> window["adrum-app-key"] = "dummy";</script>'
Essentially you have quotes mismatch.
Use this, it will fix the issue
'<script type=\'text/javascript\'> window[\'adrum-app-key\'] =\'dummy\';<\/script>'
I finally found that you cannot append script tags to head with jQuery this way.
I found some solutions here and there (look at the first code snippet of the selected answer for the second link).
The head is parsed prior to the execution of javascript. So you probably have to perform the append outside the $(document).ready function.

Why js can't understand string '</script>'? [duplicate]

This question already has answers here:
javascript variable that contains </script>
(3 answers)
Closed 8 years ago.
I have a simple javascript (jsFiddle):
alert('</script>');
Browser fails to understand it.
This is console output:
Uncaught SyntaxError: Unexpected token ILLEGAL
But this script works (jsFiddle):
alert('</scriptt>');//shows alert text '</scriptt>'
Is it some kind of browser bug or normal ECMAScript behaviour?
(browser is Chrome)
Because it is considered as:
<script>
alert('
</script>
');
which is a SyntaxError
You can use
alert( '<\/script>\n');
The HTML parser does not understand JavaScript und thus looks for something which closes the tag which is </script>. If you need '</script>' as string in JavaScript simply use '</s'+'cript>'.
JavaScript isself does not have such a problem, using var x = '</script>'; in nodejs is no problem. The HTML parser is.
This is Javascript embedded in HTML script tags, right?
Then the HTML parser terminates your script in the middle.
Put the Javascript into its own file or break up the string literal. Maybe a CDATA section also works.

java script failing because of white spaces caracters

I have in my views some code as this
$(".someclass").hover(function(){
$(this).append("#{render "layouts/show_some_file", title: "some_file"}");
});
The show_some_file.html.haml file consists of two nested basic divs
In my browser, I get
$(".someclass").hover(function(){
$(this).append("<div>
<div>some text</div>
</div>
");
});
On hover, I get in my chrome console SyntaxError: Unexpected token ILLEGAL. I deleted my white spaces in my console, and it worked. But how to clean the white spaces in my ruby rendering ?
I am not entirely certain it will help, but you probably should use the "<%= render ... %>" variant rather than the #{}
And since it's for javascript, the correct way would be "<%= escape_javascript(render ...) %>"
If using HAML, substitute the ERB for however the markup is written there.
Edit: might be
!= "$(this).append("#{escape_javascript(render "layouts/show_some_file", title: "some_file")}");"
Since the result of your {#render} is HTML, and although you might use it once, it might make more sense to store it in HTML, and retrieve it with JavaScript. Mimicking templating, here's an example of what I mean:
<script id="my_render" type="text/template">
#{render "layouts/show_some_file", title: "some_file"}
</script>
<script type="text/javascript">
$(document).ready(function () {
var render_content = $("#my_render").html();
$(".someclass").hover(function () {
$(this).append(render_content);
});
});
</script>
It kind of acts like a template. You use a script tag, but you set its type to something that doesn't cause it to be executed. Since script tags are never visible on a page, you would never have visual problems...unlike doing this inside of a div...the HTML is then "separate" from the rest of the page.
I'm sure there's a better solution using Ruby, but if you're outputting a partial view to JavaScript code, I'd have to ask why. It makes more sense to me to put in a "template". I understand this doesn't directly answer your immediate question, but it's an alternative :)
In fact, I got it, one of the right thing to do is :
$("someclass").hover(function(){
$(this).append("#{escape_javascript render "layouts/show_some_file", title: "some title"}");
});
The obvious thing to do is edit layouts/show_some_file & remove white space. It's not really whitespace that's the problem, but carriage returns. Javascript doesn't like multi-line strings. If I knew Ruby, I could probably write a regex that gets rid off stuff like "\r\n", which is carriage return line feed in PHP/C syntax.

Uncaught Reference Error:_______ is not defined

I'm a beginner with limited knowledge of both Javascript and html, sorry if my questions are very basic.
I'm trying to write a basic webpage that will do something to an array using Javascript when a button is clicked, then print the result to the page.
<!DOCTYPE html>
//error here
<html>
<head>
<title>Thursday's Homework</title>
<script>
var problem1 = function()
{for (var i = 0; i <= 50; i += 5) {
document.write(i + " ");
}
}
var myArray = []
var problem2 = function()
{for (var i = 0; i <= 9; ++i){
myArray[i]
}
document.write(myArray)
</script>
</head>
<body>
<center><h2><b> My Homework for Thursday<b></h2></center>
<p>This is my code for Problem 1:</p>
<input type="button" onclick = "problem1()" value="Does it work?">
//error here
<p>This is my code for Problem 2:</p>
<input type="button" onclick = "problem2()" value="Does it work?">
//error here
</body>
</html>
I'm getting three error messages when I debug in Chrome using developer tools:
After line 1: Uncaught SyntaxError: Unexpected end of input
After line 22(the first button): Uncaught ReferenceError: problem1 is not defined
After line 24(the second button): Uncaught Reference Error: problem2 is not defined
I'm also wondering if there's a better way to display the outputs than document.write because that makes it so that the page needs to be reloaded each time to see the next result.
I'm new, so my apologies if this is completely the wrong way to create this whole thing. If that's the case, just point me in the right direction.
UPDATE:
I've fixed the syntax errors and it's running fine. I'm still wondering about a better way to display my result that document.write. I'm not too knowledgeable, so if you have a suggestion, could you give me an idea of how to implement it?
You are missing a closing } after problem2.
That is the most common cause for this kind of error. The JS interpreter breaks since the function body is not properly closed, stops parsing. Then something else tries to reference a variable/function that failed to get parsed and triggers the Reference Error.
I can see a few issues.
You are missing a closing } after problem2.
You have spaces around your = for onclick =.
You're not actually doing anything with myArray. That does not seem intentional.
Your code formatting is unclear and that can lead to difficulties later (and I think this, in part, caused the bug). Unless you have a particularly good reason you should avoid things like {for. Instead add a newline after the {.
close the brace of problem2();
instead of document.write(); u can specify a id like
or
and in the js use
document.getElementById("abc").innerHTML=i+" ";
for better and safer coding use jsLint ..
As for you second question, you can find a lot of helpful extensions for both Chrome and Firefox that can satisfy you for debugging.
Chrome has internal tools such as "Web Console" that allow you to watch variables for exemple.

Rotator stops working when using replace

I have a problem with our website. I am trying to replace all occurrences of one phone number with different one.
If you go to www.paintballgames.co.uk you will see the regular page
If you go to www.paintballgames.co.uk/?test=phtest you will see one with changed number
However the rotator is not working in the second case.
I tried to compare source codes and only difference was, that in second case, I had some code that is changing the code displayed.
The code I am using is:
<script type="text/javascript">
var str = document.getElementById('forChange').innerHTML;
str = str.replace("844 477 5050", "844 477 5178");
document.getElementById('forChange').innerHTML = str;
</script>
Anyone can share any light on that?
First of all I see an exception with javascript even on the regular site:
$("#container-inline").html("<input type="image" name="op" value="GO" id="search-form-submit" class="form-image" />");
This will not work, as you should either escape quotes or use single quotes:
$("#container-inline").html("<input type=\"image\" name=\"op\" value=\"GO\" id=\"search-form-submit\" class=\"form-image\" />");
or
$("#container-inline").html("<input type='image' name='op' value='GO' id='search-form-submit' class='form-image' />");
UPDATE:
And one more exception in "click_heatmap.js":
Drupal.behaviors.click_heatmap = function()) {
// the "function()) {" is invalid. It should be "function() {"
click_heatmap.js:6 Uncaught SyntaxError: Unexpected token )
if (window.location.href != parent.location.href) {
$('#admin-menu').remove();
}
}
UPDATE 2:
It is possible, that after fixing the errors, you'll see the root of the problem.
UPDATE 3:
Why at all you are changing the phone number in Javascript and not on your server side?
UPDATE 4:
Now I've got even more interesting things! The 'forChange' element is almost the whole site wrapper! You should never write such code!
Instead of that you should have done this:
$(document).ready(function() {
$("SPAN.phone-now").text("your text");
});
UPDATE 5:
Now I can explain, why Javascript stops working. When you write something like body.innerHtml = body.innerHtml.replace(...) ALL the Javascript, which was there gets lost and the new one is not executed. So, nothing works! All references, which were saved in Javascript they point to not visible "old" elements.

Categories