How many characters allowed in an alert box in JavaScript

Viewed 29963

Does anyone know what is the maximum number of characters you can display in an alert box?

I'm returning an error alert to the user with details for each of the errors and warnings but apparently the box just don't show up anymore when there is too much data. Here's some of my code:

<?php
    //Two arrays are created in php, one with the errors, one with the warnings.
?>

<script type="text/javascript">
    alert("<?php
         if(count($err) != 0){
             $errorfound = True;
             echo 'Error:\n\n';
             foreach($err as $message){
                 echo '\t' . $message . '\n';
             }
         }
         if(count($warn) != 0){
             echo '\n\nWarning:\n\n';
             foreach($warn as $mess){
                 echo '\t' . $mess . '\n';
             }
        }?>");
</script>

<?php
    //app continues if no error was found
?>

After investigation, my problem didn't come from the capacity of the alert box but was in fact that I needed to addslashes() to my messages (that's why I thought it was working with fewer values, but in fact I was just lucky because they weren't characters that needed to be escaped). I'll definitely change that alert box for something more appropriated, just wanted to say that there is no problem with the alert box.

6 Answers

Test code :

<html>
  <head>
    <script>
function test ()
{
  let i;
  let nums = "";
  for ( i = 0; i <= 9999; i++ ) // ◄█■ GENERATE STRING WITH 48890 CHARS.
     nums += i.toString() + " ";
  alert( nums ); // ◄█■ DISPLAY STRING IN ALERT.
}
    </script>
  </head>
  <body onload="test()">
  </body>
</html>

When alert is displayed, copy text, paste it in Microsoft Word, and use "count characters" tool, next image is text from Firefox 84.0.2, 10000 chars :

enter image description here

Next image is from Chrome 88.0.4324.104, its alert can only hold 1833 chars :

enter image description here

Copied @Jose's answer into a snippet

function test ()
{
  let i;
  let nums = "";
  for ( i = 0; i <= 9999; i++ ) // ◄█■ GENERATE STRING WITH 48890 CHARS.
     nums += i.toString() + " ";
  alert( nums ); // ◄█■ DISPLAY STRING IN ALERT.
}
<html>
  <head>
    <script>

    </script>
  </head>
  <body onload="test()">
  </body>
</html>

Related