Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does javascript not show an alert here?

Tags:

javascript

xss

I am trying to learn XSS from Portswigger, and in its lab https://portswigger.net/web-security/cross-site-scripting/contexts/lab-javascript-string-angle-brackets-double-quotes-encoded-single-quotes-escaped, my approach yielded the following javascript code.

<script>
  var searchTerms = '\\';
  alert(1);
  \\'';
</script>

The problem is that this code shows me an error. But since Javascript is an interpreted language, shouldn't it first show the alert and then show the error?

<script>
  var searchTerms = '\\';
  alert(1);
  whatever;
</script>

Like the code snippet above is wrong as well. Here also I get an error, but the alert is also shown. So why not in the first case?

like image 800
user185887 Avatar asked Apr 07 '26 17:04

user185887


2 Answers

What you are producing in your first code is a Syntax Error. These errors occur when the JavaScript engine is parsing a script and encounters syntactically invalid code. If a JavaScript file contains a syntax error, none of the code in the file will execute.

In your second code you're not having a syntax error but instead a Semantic Error, which is why your second script will show the alert.

like image 105
Amacado Avatar answered Apr 09 '26 05:04

Amacado


The reason that the script is not working as you expect is that you're assuming that javascript will only look at one line, execute it, and then proceed to next.

However, javascript actually looks at the whole file beforehand. For example, this is demonstrated by the fact that it works to call a function which hasn't even been declared yet, but is declared lower down in the file:

showAlert();

function showAlert() {
  alert("javascript is not executed line by line");
}

If javascript only went through the file line by line, it wouldn't know the meaning of showAlert() when it first encounters it.

And if a syntax error is found, the code won't run. Note that your second example is different, because it doesn't actually have a syntax error – just the unknown whatever.

like image 25
Run_Script Avatar answered Apr 09 '26 05:04

Run_Script