简体   繁体   中英

Send JavaScript in an HTTP post request

Let's say I have foo.html and there is a text-field where I submit text that is shown afterwards on the site. It is possible to write JavaScript in this text-field. For example <script>alert(1)</script> and <script>alert(1);</script> works.

What I want to do is to send a JavaScript as message per post request to foo.html. The form has a text-area and its name is "textfield". My JavaScript code which should send another script code looks as follows:

var r = new XMLHttpRequest();
var script_code = "<script>alert(1)<\/script>";
url = "foo.html";
r.open("POST", url, false);
var content = "textfield=".concat(script_code);
r.send(content);

That works fine. But I am confused because:

var r = new XMLHttpRequest();
var script_code = "<script>alert(1);<\/script>";
url = "foo.html";
r.open("POST", url, false);
var content = "textfield=".concat(script_code);
r.send(content);

or

var r = new XMLHttpRequest();
var script_code = "<script>alert(1);\n alert(2);<\/script>";
url = "foo.html";
r.open("POST", url, false);
var content = "textfield=".concat(script_code);
r.send(content);

don't work. If I remove the semicolons it works again:

var r = new XMLHttpRequest();
var script_code = "<script>alert(1);\n alert(2);<\/script>";
script_code = script_code.replace(/;/g,"");
url = "foo.html";
r.open("POST", url, false);
var content = "textfield=".concat(script_code);
r.send(content);

But I have a much larger script saved as a string that I want to send to foo.html but it doesn't work. It doesn't work as well if I remove all semicolons. That's why my questions is: What does a "script as a string" has to look like so that this works?

EDIT: @Keith Let's say I want to try the following:

<script id=script_id> 
//TODO: What do I have to write here to decode?
var r = new XMLHttpRequest();
alert(1);
alert(2);
var script_code = document.getElementById("script_id").innerHTML;
var sub_string_begin='<script>';
var sub_string_end="<\/script>";
script_code = sub_string_begin.concat(script_code, sub_string_end);

url = "foo.html";
r.open("POST", url, false);
var content = "textfield=".concat(script_code);
content = encodeURIComponent(content);
r.send(content);
</script>

So I want to send the script itself. How do I decode it then?

It all depends on how the post request is handled by 'foo.html'.

Very likely the post request is sanitised there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM