0

I'm currently trying to create a form dynamically through javascript after looking at this post. Everything is going smoothly until when I attempt to insert javascript to the input form's value field. I am thinking of something like this

<input type = 'hidden' name = 'q' value = '<script>...some_script...</script>'

Here is my attempt at achieving what I want above

    my_form = document.createElement('form');
    my_form.name = 'form_A';
    ....

    my_tb = document.createElement('input');
    my_tb.type = 'hidden';
    my_tb.name = 'q';
    my_tb.id = 'query';
    my_tb.value = '<script>alert(document.cookie)</script>';

    my_form.appendChild(my_tb);
    document.body.appendChild(my_form);
    document.form_A.submit();

The problem is that something is wrong (or maybe even illegal) with the line my_tb.value = '<script>alert(document.cookie)</script>'; When I run the file in my browser, it prints out all the javascript in the browser after that line, and in the developer console it says Uncaught SyntaxError: Unexpected token ILLEGAL

Is there a way to achieve what I want above while still using javascript to create form_A ? The main reason is what I was hoping I can store the value of document.cookie in a variable in javascript and use it later.

Any help would be appreciated.

Community
  • 1
  • 1
user3277633
  • 1,891
  • 6
  • 28
  • 48

1 Answers1

0

Here is an example.

  1. Create index.html file and paste the below.

<html>
<head>
  <title></title>
</head>
<body>

<script>
    // your site sets a cookie
    document.cookie="username=John Doe";

    my_form = document.createElement('form');
    my_tb = document.createElement('input');
    my_tb.value = document.cookie;
    my_form.appendChild(my_tb);
    document.body.appendChild(my_form);

    alert(my_tb.value);
</script>

</body>
</html>
  1. Run a server python -m SimpleHTTPServer

  2. Open http://localhost:8000/

Dan Rasmuson
  • 5,705
  • 5
  • 29
  • 45
  • This misunderstands what the OP is trying to do. He is trying to place the script tag as the value of the input field. –  Nov 30 '15 at 06:09