<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
	<title type="html"><![CDATA[Серый форум &mdash; JS: Эмуляция браузера]]></title>
	<link rel="self" href="https://forum.script-coding.com/extern.php?action=feed&amp;tid=6289&amp;type=atom" />
	<updated>2011-10-05T11:38:51Z</updated>
	<generator>PunBB</generator>
	<id>https://forum.script-coding.com/viewtopic.php?id=6289</id>
		<entry>
			<title type="html"><![CDATA[JS: Эмуляция браузера]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=52189#p52189" />
			<content type="html"><![CDATA[<div class="quotebox"><blockquote><p>Объект <strong>Browser</strong></p><p>Имеет всего четыре метода:<br />1. Navigate (GetOrPost, URL, Param, Callback)<br />&nbsp; &nbsp; &nbsp; &nbsp;GetOrPost — обязательный параметр — принимает значения get или post<br />&nbsp; &nbsp; &nbsp; &nbsp;URL — обязательный параметр — интернет-ресурс<br />&nbsp; &nbsp; &nbsp; &nbsp;Param — обязательный параметр при post запросах<br />&nbsp; &nbsp; &nbsp; &nbsp;Callback — необязательный параметр — ссылка на функцию, которая будет вызвана сразу же после ответа сервера (и до редиректа). Функция будет вызвана с тремя параметрами status, ResponseHeaders, Response. <br />2. SubmitForm (FormNameOrIndex, Values, Callback) — ввести данные в форму и отправить<br />&nbsp; &nbsp; &nbsp; &nbsp;FormNameOrIndex — имя формы либо ее порядковый номер (с нуля).<br />&nbsp; &nbsp; &nbsp; &nbsp;Value — обязательный параметр — объект со с заданными свойствами по заполнению формы: {param1:value1, param2:value2}<br />3. ParseDocument() возвращает объект document.<br />4. ClearCookies() - очистка кукисов.</p><p>Свойства:<br />1.&nbsp; &nbsp; &nbsp;Redirect (true по умолчанию) - флаг поддержки редиректа.<br />2.&nbsp; &nbsp; Response&nbsp; - ответ сервера<br />3.&nbsp; &nbsp; ResponseHeaders&nbsp; - заголовки в ответе сервера.<br />4.&nbsp; &nbsp; UserAgent (по умолчанию &#039;Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1&#039;)<br />5.&nbsp; &nbsp; 	RefererString — URL реферера<br />6.&nbsp; &nbsp; &nbsp;Location — текущий URL<br />7.&nbsp; &nbsp; &nbsp;Cookie — флаг поддержки кукисов. (true по умолчанию)</p></blockquote></div><p>Код:<br /></p><div class="codebox"><pre><code>var CreateObject = function (ProgId) { return WScript.CreateObject(ProgId)};

function Log(e)
{
//	  WScript.Echo(e);
return e;
}

function Browser()
{
	this.XMLHTTP = CreateObject(&quot;Msxml2.ServerXMLHTTP.6.0&quot;);
	this.Redirect = true;
	this.Response = null;
	this.Referer = true;
	this.RefererString = null;
	this.ResponseHeaders = null;
	this.Location = null;
	this.__CookieStorage = &quot; &quot;;
	this.UserAgent = &#039;Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1&#039;;
	this.__Document = CreateObject(&quot;HTMLFile&quot;);
	this.Cookie = true;
}

Browser.prototype = 
{
	__ParseCookie : function (m, cookie)
	{
		if (!this.__CookieStorage) this.__CookieStorage =&quot; &quot;;
		this.__CookieStorage+=&quot; &quot;+cookie+&quot;;&quot;;
		Log(&quot;Cookie Storage:\t&quot;+this.__CookieStorage);
	},
	
	ClearCookies : function ()
	{
		this.__CookieStorage=&quot; &quot;;
	},

	Navigate : function (GetOrPost, URL, Param, Callback, RefererStr)
	{
		this.RefererString = RefererStr || this.Location;
	
		if (URL.indexOf(&quot;://&quot;)!=-1) this.Location=URL; else
		{
			if (!this.Location) return;
			this.Location = this.Location.match(/(^\w+:\/\/[\w\.]+)\//)[1]+URL;
		}
		
		URL = this.Location;
		
		if (/:\/\//.test(URL)) 
	
		Log(&quot;Navigate\t&quot;+URL);
	
		Callback = Callback || function (){}; 
		!Param? Param = null : &quot;&quot;;
		GetOrPost = GetOrPost.toUpperCase();
		
		this.XMLHTTP.open(GetOrPost, URL, false);
		this.XMLHTTP.setRequestHeader (&#039;User-agent&#039;, this.UserAgent);
		this.XMLHTTP.setRequestHeader (&quot;Content-Type&quot;, &quot;application/x-www-form-urlencoded&quot;); 
		this.XMLHTTP.setRequestHeader (&quot;Accept&quot;, &quot;text/html&quot;); 
		if (this.Referer &amp;&amp; this.RefererString)
			this.XMLHTTP.setRequestHeader (&quot;HTTP_REFERER&quot;, this.RefererString); //this.RefererString
		
		if (GetOrPost==&quot;POST&quot;) 
		{
			this.XMLHTTP.setRequestHeader (&#039;Content-length&#039;, (!Param?&quot;&quot;:Param).length);
			this.XMLHTTP.setRequestHeader (&#039;Connection&#039;, &#039;close&#039;);
		}

		if (this.Cookie &amp;&amp; this.__CookieStorage!=&quot; &quot;)
		{
			this.XMLHTTP.setRequestHeader (&quot;Cookie&quot;, this.__CookieStorage);
		}

		this.XMLHTTP.send(GetOrPost==&quot;POST&quot;? Param : null);
				
		this.ResponseHeaders = this.XMLHTTP.getAllResponseHeaders();
		this.Response = this.XMLHTTP.responseText;

		if (this.Cookie)
		{
			this.ResponseHeaders.replace(/^Set-Cookie *: *([^;]+)/igm, function( obj ){ return function (m, cookie){ obj.__ParseCookie(m, cookie) } }(this));
		}

		Log([&quot;Response status:\t&quot;+this.XMLHTTP.status, &quot;\n\nResponseHeaders:\n\n&quot;+this.ResponseHeaders, &quot;\n\nResponse:\n\n&quot;+this.Response]);
		Callback(this.XMLHTTP.status, this.ResponseHeaders, this.Response);
		
		if (this.Redirect)
		{
			var s=&quot;&quot;;
			if (this.ResponseHeaders &amp;&amp; /^Location: */im.test(this.ResponseHeaders))
			{
				s=this.ResponseHeaders.match(/^Location: *([^\n\r]+)/im)[1].toString();
				Log(&quot;Redirect to\t&quot;+s);
				this.Navigate(&quot;GET&quot;, s, null, Callback);
			}
		}
	}, 
	
	ParseDocument : function ()
	{
		var Code = (this.Response || &quot;&quot;).replace(/&lt;script([^&gt;]*)/, &quot;&lt;script type=\&quot;text/plain\&quot;&quot;);
		this.__Document.open();
		this.__Document.write(Code);
		this.__Document.close();
		return this.__Document;
	}, 
	
	SubmitForm : function (FormNameOrIndex, Values, Callback) // Values {param1:value1, param2:value2}
	{
		var DOM = this.ParseDocument();
		if (DOM.forms.length&gt;0) 
		{
			var Form = DOM.forms[FormNameOrIndex];
			var InputElements = Form.getElementsByTagName(&#039;input&#039;);
			var Result=[];
			for (var i=0, l=InputElements.length; i&lt;l; i++)
			if (InputElements[i].name &amp;&amp; InputElements[i].name!=&quot;&quot;)
			Result.push(&#039;&#039;+InputElements[i].name+&#039;=&#039;+ InputElements[i].value);
			
			Result=Result.join(&quot;&amp;&quot;);
			for (i in Values)
			{
				var re = new RegExp(&#039;(^|&amp;)&#039;+i+&quot;=[^&amp;]*&quot;,&quot;i&quot;)
				Result= Result.replace(re, &#039;$1&#039;+encodeURIComponent(i)+&quot;=&quot;+encodeURIComponent(Values[i]));
				
				if (!re.test(Result)) Result+=&quot;&amp;&quot;+encodeURIComponent(i)+&quot;=&quot;+encodeURIComponent(Values[i]);
			}
			
			Log(&quot;Serialized Form Data:\t&quot;+Result);
			this.Navigate(Form.method, Form.action, Result, Callback);
		}		
	}
}</code></pre></div><p>Использование:<br /></p><div class="codebox"><pre><code>

function callback(a,b,c)
{
	WScript.Echo([a, b, c]);
}

var WB = new Browser();

	WB.Navigate(&quot;GET&quot;, &quot;http://m.mail.ru/cgi-bin/login?noclear=1&amp;page=folders&quot;);
	WB.SubmitForm(0, {&quot;Login&quot;:&quot;***&quot;,&quot;Domain&quot;:&quot;mail.ru&quot;, &quot;Password&quot;:&quot;***&quot;});

//	WB.Navigate(&quot;GET&quot;, &quot;http://mail.ru/&quot;);
//	WB.SubmitForm(1, {&quot;Login&quot;:&quot;***&quot;,&quot;Domain&quot;:&quot;mail.ru&quot;, &quot;Password&quot;:&quot;***&quot;});


//	WB.Navigate(&quot;GET&quot;, &quot;http://vk.com/&quot;, null, callback);
//	WB.SubmitForm(0, {email:&quot;***@mail.ru&quot;, pass:&quot;***&quot;}, callback);
//	WB.Navigate(&quot;GET&quot;, &quot;http://vk.com/&quot;, null, callback);

	WScript.Echo(WB.ParseDocument().body.innerText);</code></pre></div>]]></content>
			<author>
				<name><![CDATA[JSmаn]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=24434</uri>
			</author>
			<updated>2011-10-05T11:38:51Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=52189#p52189</id>
		</entry>
</feed>
