<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
	<channel>
		<title><![CDATA[Серый форум &mdash; JS: открыть в броузере IE родительского окна не новое окно, а вкладку]]></title>
		<link>http://forum.script-coding.com/viewtopic.php?id=7691</link>
		<atom:link href="http://forum.script-coding.com/extern.php?action=feed&amp;tid=7691&amp;type=rss" rel="self" type="application/rss+xml" />
		<description><![CDATA[Недавние сообщения в теме «JS: открыть в броузере IE родительского окна не новое окно, а вкладку».]]></description>
		<lastBuildDate>Fri, 12 Oct 2012 08:07:14 +0000</lastBuildDate>
		<generator>PunBB</generator>
		<item>
			<title><![CDATA[JS: открыть в броузере IE родительского окна не новое окно, а вкладку]]></title>
			<link>http://forum.script-coding.com/viewtopic.php?pid=64719#p64719</link>
			<description><![CDATA[<p>Возникла мысль, как упростить открытие в IE размещенных в тестовых комментах сайтов специально видоизмененных ссылок - с добавленными в адрес пробелами и всякими спец.символами. </p><p>Идею оформил простенькой html-страничкой, вызываемой из контекстноого меню при выделении такой &quot;битой ссылки&quot;. Скрипт пробует убрать явно лишние символы, добавляет &quot;http://&quot; (если не было), тестирует доступность адреса методом приведенным в ветке <a href="http://forum.script-coding.com/viewtopic.php?pid=59923#p59923">JavaScript: как получить по javascript-ссылке адрес для загрузки файла</a>, если тест успешен, то страничка со скриптом закрывается, а ссылка без лишних вопросов открывается в новом окне IE, если тест неуспешен, то дается возможность перед запуском перехода адрес подправить.</p><p>Вот, текст страницы <strong>IE_OpenAddrInNewWin.htm</strong>:<br /></p><div class="codebox"><pre><code>&lt;!-- IE_OpenAddrInNewWin.htm
Данная страничка выполняет удаление явно некорректных символов в выделенном тексте,
далее полученный текст проверяется в качестве корректного адреса - если с адреса получен положительный ответ,
то он передает  новому окну Internet Explorer, иначе - предлагается предварительно его подкорректировать в дополнительном диалоге

Меню вызова этой страницы при выделения в броузере текста настраивается запуском скрипта - &quot;IE_OpenAddrInNewWin_setup.vbs&quot;. 
--&gt;

&lt;html style=&quot;width: 400px; height: 220px; margin: 10px; status:1&quot;&gt;
&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=windows-1251&quot;&gt;
&lt;meta name=&quot;Author&quot; content=&quot;R.G.&quot;&gt;
&lt;meta name=&quot;Description&quot; content=&quot;Preparate-test url, open url in new window&quot;&gt;

&lt;head&gt;
&lt;title&gt;Open in New Window...&lt;/title&gt;
&lt;/head&gt;

&lt;!-- ========================================= HTML ===========================================  --&gt;

&lt;BODY BGCOLOR=&quot;#C0C0C0&quot; onload=&quot;Window_OnLoad();&quot;&gt;
&lt;div align=&quot;center&quot;&gt;&lt;small&gt;[&lt;span id=&quot;id_recvText&quot; style=&quot;color:blue&quot; title=&quot;Полученный с родительского окна выделенный текст&quot;&gt;&lt;/span&gt;]&lt;/div&gt;
&lt;br&gt;

&lt;input type=&quot;text&quot; name=&quot;tParam&quot; size=&quot;70&quot; Value=&quot;&quot; 
style=&quot;font-family: Arial; font-size: 11;&quot;
title=&#039;Адрес для запуска. &lt;Enter&gt; - открытие адреса в новом окне&#039;&gt;
&lt;br&gt;

&lt;div align=&quot;center&quot;&gt;

&lt;input id=btGo type=submit value=&quot;Go to address&quot; 
	onclick=&quot;var url=document.getElementById(&#039;tParam&#039;).value;
		var win=window.open(url); win.focus(); window.close();&quot; 
	style=&quot;{font-family: Arial; font-size: 12;}&quot; 
	title=&quot;Открытие адреса в новом окне&quot;&gt;

&lt;input type=button value=&quot;Close&quot; onclick=&quot;window.close();&quot; style=&quot;{font-family: Arial; font-size: 11;}&quot; 
	title=&quot;Закрытие окна&quot;&gt;
	
&lt;div id=&quot;divErrMsg&quot; style=&quot;color:Blue&quot; title=&quot;Статус теста полученного адреса&quot;&gt;
&lt;br&gt;
&lt;br&gt;&lt;br&gt;&lt;br&gt;
&lt;/div&gt;
&lt;hr&gt;
&lt;i&gt;&amp;nbsp;IE_OpenAddrInNewWin.htm v0.2 by 11.10.2012 &amp;nbsp; &amp;copy; R.G.&lt;/i&gt;
&lt;/div&gt;

&lt;!-- ====================================== VBScript ==========================================  --&gt;
&lt;script language=&quot;VBScript&quot;&gt;

&#039;--- uf_repairAddress() 
&#039; Из строки убираются недопустимые в url символы 
&#039; в начало, если не было, добавляется протокол &quot;http://&quot;
Function uf_repairAddress(pText)
	ret = pText
	ret = Trim(ret)
	&#039;--- сначала удаляем http://&#039;
	iPos = InStr(1, ret, &quot;http://&quot;, 1) : If iPos &gt; 0 Then ret = Right(ret, Len(ret) - iPos - 6)
	&#039;--- Убираем явно недопустимые символы&#039;
	&#039;(символ % не трогаем специально, т.к. это может быть кодирование какого-то ASCII-Character)&#039;
	ret = Replace(ret,&quot;//&quot;,&quot;&quot;)
	ret = Replace(ret,&quot;\&quot;,&quot;&quot;)
	ret = Replace(ret,&quot;!&quot;,&quot;&quot;)
	ret = Replace(ret,&quot;@&quot;,&quot;&quot;)
	ret = Replace(ret,&quot;$&quot;,&quot;&quot;)
	ret = Replace(ret,&quot;^&quot;,&quot;&quot;)
	ret = Replace(ret,&quot;&amp;&quot;,&quot;&quot;)
	ret = Replace(ret,&quot;*&quot;,&quot;&quot;)
	ret = Replace(ret,&quot;+&quot;,&quot;&quot;)
	ret = Replace(ret,&quot;(&quot;,&quot;&quot;)
	ret = Replace(ret,&quot;)&quot;,&quot;&quot;)
	ret = Replace(ret,&quot;&lt;&quot;,&quot;&quot;)
	ret = Replace(ret,&quot;&gt;&quot;,&quot;&quot;)
	ret = Replace(ret,&quot;[&quot;,&quot;&quot;)
	ret = Replace(ret,&quot;]&quot;,&quot;&quot;)
	ret = Replace(ret,&quot;&quot;&quot;&quot;,&quot;&quot;)
	ret = Replace(ret,&quot;&#039;&quot;,&quot;&quot;)
	ret = Replace(ret,&quot;:&quot;,&quot;&quot;)
	ret = Replace(ret,&quot;;&quot;,&quot;&quot;)
	ret = Replace(ret,&quot; &quot;,&quot;&quot;)
	ret = Replace(ret,&quot;•&quot;,&quot;&quot;)
	ret = Replace(ret,&quot;—&quot;,&quot;&quot;)
	ret = Replace(ret,&quot;‘&quot;,&quot;&quot;)
	ret = Replace(ret,&quot;’&quot;,&quot;&quot;)
	ret = Replace(ret,&quot;“&quot;,&quot;&quot;)
	ret = Replace(ret,&quot;”&quot;,&quot;&quot;)
	For i=192 To 255 &#039;--- в цикле - замена кириллического текста&#039;
		ret = Replace(ret,Chr(i),&quot;&quot;)
	Next
	&#039;--- добавляем http://&#039;
	ret = &quot;http://&quot; &amp; ret
	uf_repairAddress = ret
END FUNCTION

&#039;--- &#039;uf_testUrl()
&#039; Проверяется доступность адреса ссылки
&#039; &quot;&quot; - возвращается при статусе &quot;ОК&quot;, иначе - текст ошибки&#039;
Function uf_testUrl(pUrl) 
	uf_testUrl = &quot;no data&quot;
	
	&#039;--- Если в проверяемом адресе есть #, укорачиваем урл до этого символа&#039;
	iPos = InStr(pUrl,&quot;#&quot;) : If iPos&gt;0 Then pUrl = Left(pUrl, iPos - 1)
	
	On Error Resume Next
	Dim xmlhttp : Set xmlhttp = CreateObject(&quot;Microsoft.XMLHTTP&quot;)
	xmlhttp.open &quot;GET&quot;, pUrl, False
	xmlhttp.send
 
	If xmlhttp.status &lt;&gt; 200 Then
		uf_testUrl = &quot;&lt;hr&gt;status: &quot; &amp; xmlhttp.status &amp; &quot;&lt;br&gt;&quot; &amp; xmlhttp.statusText
	else
		uf_testUrl = &quot;&quot;
	End If
	On Error GoTo 0
END FUNCTION


&lt;/script&gt;

&lt;!-- =================================== JScript ==============================================  --&gt;
&lt;script language=&quot;JavaScript&quot;&gt;

var parentwin;
var doc;

// отрабатывает при открытии окна - получение значений из &quot;вызвавшей&quot; страницы
function Window_OnLoad()
{
	parentwin = external.menuArguments;     // получаем объект окна
	doc = parentwin.document;               // получаем объект документа
	
	var sel = doc.selection.createRange().text; // получаем текст выделения
	
	document.all.id_recvText.insertAdjacentHTML (&quot;beforeEnd&quot;, sel); // отображаем полученный текст
	
	tParam.value = uf_repairAddress(sel);
	var errTestUrl = uf_testUrl(tParam.value);
	if (errTestUrl) document.all.divErrMsg.innerHTML=errTestUrl; else btGo.onclick();

}

&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;</code></pre></div><p>Вот, скрипт <strong>IE_OpenAddrInNewWin_setup.vbs</strong> для настройки меню:<br /></p><div class="codebox"><pre><code>
&#039; IE_OpenAddrInNewWin_setup.vbs
&#039; ----------------------------------------------------------------------------------------
&#039; Добавляет/Удаляет в контекстное меню Internet Explorer пункт
&#039; ----------------------------------------------------------------------------------------

&#039;--- имя добавляемого пункта
Const csMenu = &quot;_Open selected HTTP-Address in New Window&quot;

&#039;--- имя прописываемого для пункта HTML-файла
Const csFile = &quot;IE_OpenAddrInNewWin.htm&quot;

&#039;--- описание фцнкционала добавляемого пункта
Const csDescription = &quot;для добавления возможности открытия выделенного на странице адреса в новом окне&quot;


Dim WshShell, FSO
Set WshShell = WScript.CreateObject(&quot;WScript.Shell&quot;)
Set FSO = WScript.CreateObject(&quot;Scripting.FileSystemObject&quot;)

Dim REG_MENUEXT, REG_NEWMENU, rc, sPathApp, sPathHTM
REG_MENUEXT = &quot;HKCU\Software\Microsoft\Internet Explorer\MenuExt\&quot; &#039; путь к меню Internet Explorer в реестре
sPathApp = fso.GetAbsolutePathName(&quot;.&quot;) &#039;путь к каталогу запуска задачи&#039;
sPathHTM = sPathApp &amp; &quot;\&quot; &amp; csFile &#039;полный путь к HTML-странице

&#039;--- проверка наличия в IE нашего пункта&#039;
If uf_keyExists( REG_MENUEXT &amp; csMenu &amp; &quot;\&quot; ) Then 
	&#039;--- менюшка уже есть, предлагаем удалить&#039;
	rc=MsgBox(&quot;Удалять из меню Internet Explorer данный пункт ?&quot; &amp; vbCrLf &amp; vbCrLf &amp; _
	&quot;Назначение пункта: &quot; &amp; csDescription &amp; &quot;.&quot;, vbQuestion + vbOKCancel, csMenu)
	If rc=vbOK Then
		WshShell.RegDelete( REG_MENUEXT &amp; csMenu &amp; &quot;\&quot; )
		MsgBox &quot;Удаление выполнено.&quot; &amp; vbCrLf &amp;_
			&quot;Перезапустите Internet Explorer, чтобы изменения вступили в силу&quot; &amp; vbCrLf &amp; vbCrLf, _
			vbInformation, &quot;Удаление в IE меню &quot;&quot;&quot; &amp; csMenu &amp; &quot;&quot;&quot;&quot;
	End IF
else &#039;--- пункта меню нет, предлагаем установить&#039;
	rc = MsgBox(&quot;Хотите добавить в контекстное меню Internet Explorer пункт &quot;&quot;&quot; &amp; csMenu &amp; &quot;&quot;&quot;&quot; &amp; vbCrLf &amp; vbCrLf &amp; _
		csDescription &amp; vbCrLf &amp; vbCrLf, _
		vbYesNo OR vbQuestion, &quot;Установка &quot;&quot;&quot; &amp; csMenu &amp; &quot;&quot;&quot;&quot;)
	If rc=vbYes Then
		&#039; Записываем в реестр требуемые значения
		REG_NEWMENU = REG_MENUEXT &amp; csMenu &amp; &quot;\&quot;
		WshShell.RegWrite REG_NEWMENU, sPathHTM, &quot;REG_SZ&quot;
		WshShell.RegWrite REG_NEWMENU &amp; &quot;Contexts&quot;, 4+8+16+32, &quot;REG_DWORD&quot; &#039;Controls + Tables + Text selection + Anchor&#039;
		WshShell.RegWrite REG_NEWMENU &amp; &quot;Flags&quot;,    1, &quot;REG_DWORD&quot;
		WshShell.RegWrite REG_NEWMENU &amp; &quot;My_Desccription&quot;, csDescription, &quot;REG_SZ&quot; &#039;Собственный.параметр реестра - описание пункта&#039;
		MsgBox &quot;Данные были успешно внесены,&quot; &amp; vbCrLf &amp; _
			&quot;путь к программе прописан следующий - &quot;&quot;&quot;&amp;sPathHTM&amp;&quot;&quot;&quot;.&quot; &amp; vbCrLf &amp; vbCrLf &amp; _
			&quot;Перезапустите Internet Explorer, чтобы изменения вступили в силу, &quot; &amp;_
			&quot;добавленный пункт будет отображаться в контекстном меню при наличии выделенного на странице текста.&quot; &amp; vbCrLf &amp;vbCrLf,_
			vbInformation, csMenu
	End IF
End If

Set FSO = Nothing
Set WshShell = Nothing


&#039;--- проверка наличия ключа реестра&#039;
Function uf_keyExists(key)
  Dim key2    
  On Error Resume Next
  key2 = WshShell.RegRead(key)
  If Err &lt;&gt; 0 Then
    uf_keyExists = False
  Else
    uf_keyExists = True
  End If
  On Error GoTo 0
End Function</code></pre></div><p>Имхо, получилось довольно удобно открывать такие ссылки, но <strong>еще хотелось бы, чтобы по возможности открывалось не новое окно броузера, а новая вкладка</strong>.</p><p>В строке:<br /></p><div class="codebox"><pre><code>onclick=&quot;var url=document.getElementById(&#039;tParam&#039;).value;
        var win=window.open(url); win.focus(); window.close();&quot;</code></pre></div><p>пробовал &quot;методом тыка&quot; изменять &quot;window.open(url);&quot; на &quot;window.open(url,<strong>&#039;_blank&#039;</strong>);&quot;, на &quot;<strong>parentwin.</strong>open(...);&quot; - открытие в новой вкладке так и не добился.<br />Прошу Вашей подсказки.</p>]]></description>
			<author><![CDATA[null@example.com (Rom5)]]></author>
			<pubDate>Fri, 12 Oct 2012 08:07:14 +0000</pubDate>
			<guid>http://forum.script-coding.com/viewtopic.php?pid=64719#p64719</guid>
		</item>
	</channel>
</rss>
