Перейти к контенту
  • 0

BB-код для HTML


Вопрос

Так, как на вопрос про Silverlight мне никто не ответил, у меня другой вопрос - а нет ли BB-кода, позволяющего вставлять HTML? Можно и в виде фрейма, только чтобы это было внутри сообщения/темы
Ссылка на комментарий
Поделиться на других сайтах

Рекомендуемые сообщения

  • 0
ЧТО именно надо вставлять, и ПОЧЕМУ нельзя сделать это доступным простым смертным, соблюдая все правила безопасности

Да те же флеши к примеру.

Например в аттаче флешка размером 250 байт, просто прозрачное поле. Алерт на движения мыши.

alert.zip

Ссылка на комментарий
Поделиться на других сайтах

  • 0

Блин, Ritsuka, следите за исходящим трафиком! Я говорю о Silverlight 2 - она, в отличие от первой версии, работает на .NET, а не на уже засранном java!

А то что мне там приводят, что код на XAML - это java - голову на отсечение

Ссылка на комментарий
Поделиться на других сайтах

  • 0
Блин, Ritsuka, следите за исходящим трафиком! Я говорю о Silverlight 2 - она, в отличие от первой версии, работает на .NET, а не на уже засранном java!

А то что мне там приводят, что код на XAML - это java - голову на отсечение

 

1. Открываем http://www.microsoft.com/rus/expression/re...es/Default.aspx

2. Качаем книгу "Введение в Microsoft® Silverlight™ 2" и читаем.

3. Качаем "Исходные коды примеров, используемых в книге" в двух частях.

4. Открываем любой код примера.

 

Если вы и после этого будете мне рассказывать про то, что Silverlight 2 не использует Javascript, то мы живем в разных вселенных.

 

С другой стороны - всем пофиг. Javascript, не Javascript, да хоть код на коболе. Главное - приведите наконец пример кода, который нужно вставлять в сообщения. Вас уже попросили об этом все по два раза. Пока не приведете, помочь вам никто не сможет.

 

------------------------------------------------------------------

 

Так как вы явно физически не способны понять, что от вас хотят, самостоятельно проведу разбор на тему, что же это за зверь - Silverlight.

 

Есть две схемы использования:

 

1. Javascript (основная, почти вся книга посвящена ей).

 

Рассмотрим её на примере приложения "DragDrop" из 6-й главы. Листинг кода:

 

Default.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!-- saved from url=(0014)about:internet -->
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>DragDrop</title>

<script type="text/javascript" src="Silverlight.js"></script>
<script type="text/javascript" src="Page.xaml.js"></script>
<script type="text/javascript">
var beginX; 
var beginY; 
var isMouseDown = false; 
function onMouseDown(sender, mouseEventArgs) 
{ 
   beginX = mouseEventArgs.getPosition(null).x; 
   beginY = mouseEventArgs.getPosition(null).y; 
   isMouseDown = true; 
   sender.captureMouse(); 
}
function onMouseMove(sender, mouseEventArgs) 
{ 
 if (isMouseDown == true) 
   { 
       var currX = mouseEventArgs.getPosition(null).x; 
       var currY = mouseEventArgs.getPosition(null).y; 
       sender["Canvas.Left"] += currX - beginX; 
       sender["Canvas.Top"] += currY - beginY; 
       beginX = currX; 
       beginY = currY; 
   } 
}
function onMouseUp(sender, mouseEventArgs) 
{ 
   isMouseDown = false; 
   sender.releaseMouseCapture(); 
}

</script>
<style type="text/css">
	#silverlightControlHost {
		height: 480px;
		width: 640px;
	}
	#errorLocation {
		font-size: small;
		color: Gray;
	}
</style>
<script type="text/javascript">
	function createSilverlight()
	{
		var scene = new DragDrop.Page();
		Silverlight.createObjectEx({
			source: "Page.xaml",
			parentElement: document.getElementById("silverlightControlHost"),
			id: "SilverlightControl",
			properties: {
				width: "100%",
				height: "100%",
				version: "1.0"
			},
			events: {
				onLoad: Silverlight.createDelegate(scene, scene.handleLoad),
				onError: function(sender, args) {
					var errorDiv = document.getElementById("errorLocation");
					if (errorDiv != null) {
						var errorText = args.errorType + "- " + args.errorMessage;

						if (args.ErrorType == "ParserError") {
							errorText += "<br>File: " + args.xamlFile;
							errorText += ", line " + args.lineNumber;
							errorText += " character " + args.charPosition;
						}
						else if (args.ErrorType == "RuntimeError") {
							errorText += "<br>line " + args.lineNumber;
							errorText += " character " +  args.charPosition;
						}
						errorDiv.innerHTML = errorText;
					}	
				}
			}
		});
	}


	if (!window.Silverlight) 
		Silverlight = {};

	Silverlight.createDelegate = function(instance, method) {
		return function() {
			return method.apply(instance, arguments);
		}
	}
</script>
</head>

<body>
<div id="silverlightControlHost">
	<script type="text/javascript">
	    createSilverlight();
	</script>
</div>

<!-- Runtime errors from Silverlight will be displayed here.
This will contain debugging information and should be removed or hidden when debugging is completed -->
<div id='errorLocation'></div>
</body>
</html>

 

Page.xaml

<Canvas
xmlns="http://schemas.microsoft.com/client/2007"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="640" Height="480"
Background="White"
x:Name="Page">
<Canvas xmlns="http://schemas.microsoft.com/client/2007" 
       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
       Height="400" Width="400"> 
<Ellipse Canvas.Top="0" Height="10" Width="10" Fill="Black" 
        MouseLeftButtonDown="onMouseDown" 
        MouseLeftButtonUp="onMouseUp" 
        MouseMove="onMouseMove" /> 
<Ellipse Canvas.Top="20" Height="10" Width="10" Fill="Black" 
        MouseLeftButtonDown="onMouseDown" 
        MouseLeftButtonUp="onMouseUp" 
        MouseMove="onMouseMove"/> 
<Ellipse Canvas.Top="40" Height="10" Width="10" Fill="Black" 
        MouseLeftButtonDown="onMouseDown" 
        MouseLeftButtonUp="onMouseUp" 
        MouseMove="onMouseMove"/> 
<Ellipse Canvas.Top="60" Height="10" Width="10" Fill="Black" 
        MouseLeftButtonDown="onMouseDown" 
        MouseLeftButtonUp="onMouseUp" 
        MouseMove="onMouseMove"/> 
</Canvas>

</Canvas>

 

Page.xaml.js

if (!window.DragDrop)
DragDrop = {};

DragDrop.Page = function() 
{
}

DragDrop.Page.prototype =
{
handleLoad: function(control, userContext, rootElement) 
{
	this.control = control;

	// Sample event hookup:	
	rootElement.addEventListener("MouseLeftButtonDown", Silverlight.createDelegate(this, this.handleMouseDown));
},

// Sample event handler
handleMouseDown: function(sender, eventArgs) 
{
	// The following line of code shows how to find an element by name and call a method on it.
	// this.control.content.findName("Storyboard1").Begin();
}
}

 

Silverlight.js

if (!window.Silverlight)
{
   window.Silverlight = { };
}

// Silverlight control instance counter for memory mgt
Silverlight._silverlightCount = 0;
Silverlight.fwlinkRoot='http://go2.microsoft.com/fwlink/?LinkID=';  
Silverlight.onGetSilverlight = null;
Silverlight.onSilverlightInstalled = function () {window.location.reload(false);};

//////////////////////////////////////////////////////////////////
// isInstalled, checks to see if the correct version is installed
//////////////////////////////////////////////////////////////////
Silverlight.isInstalled = function(version)
{
   var isVersionSupported=false;
   var container = null;

   try 
   {
       var control = null;

       try
       {
           control = new ActiveXObject('AgControl.AgControl');
           if ( version == null )
           {
               isVersionSupported = true;
           }
           else if ( control.IsVersionSupported(version) )
           {
               isVersionSupported = true;
           }
           control = null;
       }
       catch (e)
       {
           var plugin = navigator.plugins["Silverlight Plug-In"] ;
           if ( plugin )
           {
               if ( version === null )
               {
                   isVersionSupported = true;
               }
               else
               {
                   var actualVer = plugin.description;
                   if ( actualVer === "1.0.30226.2")
                       actualVer = "2.0.30226.2";
                   var actualVerArray =actualVer.split(".");
                   while ( actualVerArray.length > 3)
                   {
                       actualVerArray.pop();
                   }
                   while ( actualVerArray.length < 4)
                   {
                       actualVerArray.push(0);
                   }
                   var reqVerArray = version.split(".");
                   while ( reqVerArray.length > 4)
                   {
                       reqVerArray.pop();
                   }

                   var requiredVersionPart ;
                   var actualVersionPart
                   var index = 0;


                   do
                   {
                       requiredVersionPart = parseInt(reqVerArray[index]);
                       actualVersionPart = parseInt(actualVerArray[index]);
                       index++;
                   }
                   while (index < reqVerArray.length && requiredVersionPart === actualVersionPart);

                   if ( requiredVersionPart <= actualVersionPart && !isNaN(requiredVersionPart) )
                   {
                       isVersionSupported = true;
                   }
               }
           }
       }
   }
   catch (e) 
   {
       isVersionSupported = false;
   }
   if (container) 
   {
       document.body.removeChild(container);
   }

   return isVersionSupported;
}
Silverlight.WaitForInstallCompletion = function()
{
   if ( ! Silverlight.isBrowserRestartRequired && Silverlight.onSilverlightInstalled )
   {
       try
       {
           navigator.plugins.refresh();
       }
       catch(e)
       {
       }
       if ( Silverlight.isInstalled(null) )
       {
           Silverlight.onSilverlightInstalled();
       }
       else
       {
             setTimeout(Silverlight.WaitForInstallCompletion, 3000);
       }    
   }
}
Silverlight.__startup = function()
{
   Silverlight.isBrowserRestartRequired = Silverlight.isInstalled(null);//(!window.ActiveXObject || Silverlight.isInstalled(null));
   if ( !Silverlight.isBrowserRestartRequired)
   {
       Silverlight.WaitForInstallCompletion();
   }
   if (window.removeEventListener) { 
      window.removeEventListener('load', Silverlight.__startup , false);
   }
   else { 
       window.detachEvent('onload', Silverlight.__startup );
   }
}

if (window.addEventListener) 
{
   window.addEventListener('load', Silverlight.__startup , false);
}
else 
{
   window.attachEvent('onload', Silverlight.__startup );
}

///////////////////////////////////////////////////////////////////////////////
// createObject();  Params:
// parentElement of type Element, the parent element of the Silverlight Control
// source of type String
// id of type string
// properties of type String, object literal notation { name:value, name:value, name:value},
//     current properties are: width, height, background, framerate, isWindowless, enableHtmlAccess, inplaceInstallPrompt:  all are of type string
// events of type String, object literal notation { name:value, name:value, name:value},
//     current events are onLoad onError, both are type string
// initParams of type Object or object literal notation { name:value, name:value, name:value}
// userContext of type Object
/////////////////////////////////////////////////////////////////////////////////

Silverlight.createObject = function(source, parentElement, id, properties, events, initParams, userContext)
{
   var slPluginHelper = new Object();
   var slProperties = properties;
   var slEvents = events;

   slPluginHelper.version = slProperties.version;
   slProperties.source = source;    
   slPluginHelper.alt = slProperties.alt;

   //rename properties to their tag ibresource names
   if ( initParams )
       slProperties.initParams = initParams;
   if ( slProperties.isWindowless && !slProperties.windowless)
       slProperties.windowless = slProperties.isWindowless;
   if ( slProperties.framerate && !slProperties.maxFramerate)
       slProperties.maxFramerate = slProperties.framerate;
   if ( id && !slProperties.id)
       slProperties.id = id;

   // remove elements which are not to be added to the instantiation tag
   delete slProperties.ignoreBrowserVer;
   delete slProperties.inplaceInstallPrompt;
   delete slProperties.version;
   delete slProperties.isWindowless;
   delete slProperties.framerate;
   delete slProperties.data;
   delete slProperties.src;
   delete slProperties.alt;


   // detect that the correct version of Silverlight is installed, else display install

   if (Silverlight.isInstalled(slPluginHelper.version))
   {
       //move unknown events to the slProperties array
       for (var name in slEvents)
       {
           if ( slEvents[name])
           {
               if ( name == "onLoad" && typeof slEvents[name] == "function" && slEvents[name].length != 1 )
               {
                   var onLoadHandler = slEvents[name];
                   slEvents[name]=function (sender){ return onLoadHandler(document.getElementById(id), userContext, sender)};
               }
               var handlerName = Silverlight.__getHandlerName(slEvents[name]);
               if ( handlerName != null )
               {
                   slProperties[name] = handlerName;
                   slEvents[name] = null;
               }
               else
               {
                   throw "typeof events."+name+" must be 'function' or 'string'";
               }
           }
       }
       slPluginHTML = Silverlight.buildHTML(slProperties);
   }
   //The control could not be instantiated. Show the installation prompt
   else 
   {
       slPluginHTML = Silverlight.buildPromptHTML(slPluginHelper);
   }

   // insert or return the HTML
   if(parentElement)
   {
       parentElement.innerHTML = slPluginHTML;
   }
   else
   {
       return slPluginHTML;
   }

}

///////////////////////////////////////////////////////////////////////////////
//
//  create HTML that instantiates the control
//
///////////////////////////////////////////////////////////////////////////////
Silverlight.buildHTML = function( slProperties)
{
   var htmlBuilder = [];

   htmlBuilder.push('<object type=\"application/x-silverlight\" data="data:application/x-silverlight,"');
   if ( slProperties.id != null )
   {
       htmlBuilder.push(' id="' + slProperties.id + '"');
   }
   if ( slProperties.width != null )
   {
       htmlBuilder.push(' width="' + slProperties.width+ '"');
   }
   if ( slProperties.height != null )
   {
       htmlBuilder.push(' height="' + slProperties.height + '"');
   }
   htmlBuilder.push(' >');

   delete slProperties.id;
   delete slProperties.width;
   delete slProperties.height;

   for (var name in slProperties)
   {
       if (slProperties[name])
       {
           htmlBuilder.push('<param name="'+Silverlight.HtmlAttributeEncode(name)+'" value="'+Silverlight.HtmlAttributeEncode(slProperties[name])+'" />');
       }
   }
   htmlBuilder.push('<\/object>');
   return htmlBuilder.join('');
}




// createObjectEx, takes a single parameter of all createObject parameters enclosed in {}
Silverlight.createObjectEx = function(params)
{
   var parameters = params;
   var html = Silverlight.createObject(parameters.source, parameters.parentElement, parameters.id, parameters.properties, parameters.events, parameters.initParams, parameters.context);
   if (parameters.parentElement == null)
   {
       return html;
   }
}

///////////////////////////////////////////////////////////////////////////////////////////////
// Builds the HTML to prompt the user to download and install Silverlight
///////////////////////////////////////////////////////////////////////////////////////////////
Silverlight.buildPromptHTML = function(slPluginHelper)
{
   var slPluginHTML = "";
   var urlRoot = Silverlight.fwlinkRoot;
   var shortVer = slPluginHelper.version ;
   if ( slPluginHelper.alt )
   {
       slPluginHTML = slPluginHelper.alt;
   }
   else
   {
       if (! shortVer )
       {
           shortVer="";
       }
       slPluginHTML = "<a href='java script:Silverlight.getSilverlight(\"{1}\");' style='text-decoration: none;'><img src='{2}' alt='Get Microsoft Silverlight' style='border-style: none'/></a>";
       slPluginHTML = slPluginHTML.replace('{1}', shortVer );
       slPluginHTML = slPluginHTML.replace('{2}', urlRoot + '108181');
   }

   return slPluginHTML;
}


Silverlight.getSilverlight = function(version)
{
   if (Silverlight.onGetSilverlight )
   {
       Silverlight.onGetSilverlight();
   }

   var shortVer = "";
   var reqVerArray = String(version).split(".");
   if (reqVerArray.length > 1)
   {
       var majorNum = parseInt(reqVerArray[0] );
       if ( isNaN(majorNum) || majorNum < 2 )
       {
           shortVer = "1.0";
       }
       else
       {
           shortVer = reqVerArray[0]+'.'+reqVerArray[1];
       }
   }

   var verArg = "";

   if (shortVer.match(/^\d+\056\d+$/) )
   {
       verArg = "&v="+shortVer;
   }

   Silverlight.followFWLink("114576" + verArg);
}


///////////////////////////////////////////////////////////////////////////////////////////////
/// Navigates to a url based on fwlinkid
///////////////////////////////////////////////////////////////////////////////////////////////
Silverlight.followFWLink = function(linkid)
{
   top.location=Silverlight.fwlinkRoot+String(linkid);
}












///////////////////////////////////////////////////////////////////////////////////////////////
/// Encodes special characters in input strings as charcodes
///////////////////////////////////////////////////////////////////////////////////////////////
Silverlight.HtmlAttributeEncode = function( strInput )
{
     var c;
     var retVal = '';

   if(strInput == null)
     {
         return null;
   }

     for(var cnt = 0; cnt < strInput.length; cnt++)
     {
           c = strInput.charCodeAt(cnt);

           if (( ( c > 96 ) && ( c < 123 ) ) ||
                 ( ( c > 64 ) && ( c < 91 ) ) ||
                 ( ( c > 43 ) && ( c < 58 ) && (c!=47)) ||
                 ( c == 95 ))
           {
                 retVal = retVal + String.fromCharCode©;
           }
           else
           {
                 retVal = retVal + '' + c + ';';
           }
     }

     return retVal;
}
///////////////////////////////////////////////////////////////////////////////
//
//  Default error handling function to be used when a custom error handler is
//  not present
//
///////////////////////////////////////////////////////////////////////////////

Silverlight.default_error_handler = function (sender, args)
{
   var iErrorCode;
   var errorType = args.ErrorType;

   iErrorCode = args.ErrorCode;

   var errMsg = "\nSilverlight error message     \n" ;

   errMsg += "ErrorCode: "+ iErrorCode + "\n";


   errMsg += "ErrorType: " + errorType + "       \n";
   errMsg += "Message: " + args.ErrorMessage + "     \n";

   if (errorType == "ParserError")
   {
       errMsg += "XamlFile: " + args.xamlFile + "     \n";
       errMsg += "Line: " + args.lineNumber + "     \n";
       errMsg += "Position: " + args.charPosition + "     \n";
   }
   else if (errorType == "RuntimeError")
   {
       if (args.lineNumber != 0)
       {
           errMsg += "Line: " + args.lineNumber + "     \n";
           errMsg += "Position: " +  args.charPosition + "     \n";
       }
       errMsg += "MethodName: " + args.methodName + "     \n";
   }
   alert (errMsg);
}

///////////////////////////////////////////////////////////////////////////////////////////////
/// Releases event handler resources when the page is unloaded
///////////////////////////////////////////////////////////////////////////////////////////////
Silverlight.__cleanup = function ()
{
   for (var i = Silverlight._silverlightCount - 1; i >= 0; i--) {
       window['__slEvent' + i] = null;
   }
   Silverlight._silverlightCount = 0;
   if (window.removeEventListener) { 
      window.removeEventListener('unload', Silverlight.__cleanup , false);
   }
   else { 
       window.detachEvent('onunload', Silverlight.__cleanup );
   }
}
///////////////////////////////////////////////////////////////////////////////////////////////
/// Releases event handler resources when the page is unloaded
///////////////////////////////////////////////////////////////////////////////////////////////
Silverlight.__getHandlerName = function (handler)
{
   var handlerName = "";
   if ( typeof handler == "string")
   {
       handlerName = handler;
   }
   else if ( typeof handler == "function" )
   {
       if (Silverlight._silverlightCount == 0)
       {
           if (window.addEventListener) 
           {
               window.addEventListener('onunload', Silverlight.__cleanup , false);
           }
           else 
           {
               window.attachEvent('onunload', Silverlight.__cleanup );
           }
       }
       var count = Silverlight._silverlightCount++;
       handlerName = "__slEvent"+count;

       window[handlerName]=handler;
   }
   else
   {
       handlerName = null;
   }
   return handlerName;
}

 

Web.config

<?xml version="1.0"?>
<!-- 
   Note: As an alternative to hand editing this file you can use the 
   web admin tool to configure settings for your application. Use
   the Website->Asp.Net Configuration option in Visual Studio.
   A full list of settings and comments can be found in 
   machine.config.comments usually located in 
   \Windows\Microsoft.Net\Framework\v2.x\Config 
-->
<configuration>
<appSettings/>
<connectionStrings/>
<system.web>
	<!-- 
           Set compilation debug="true" to insert debugging 
           symbols into the compiled page. Because this 
           affects performance, set this value to true only 
           during development.
       -->
	<compilation debug="true">
	</compilation>
	<!--
           The <authentication> section enables configuration 
           of the security authentication mode used by 
           ASP.NET to identify an incoming user. 
       -->
	<authentication mode="Windows"/>
	<!--
           The <customErrors> section enables configuration 
           of what to do if/when an unhandled error occurs 
           during the execution of a request. Specifically, 
           it enables developers to configure html error pages 
           to be displayed in place of a error stack trace.

       <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
           <error statusCode="403" redirect="NoAccess.htm" />
           <error statusCode="404" redirect="FileNotFound.htm" />
       </customErrors>
       -->
</system.web>
</configuration>

Как видим, все базируется именно на "засранном java", и втыкать такое в форум - мэднесс в чистом виде.

 

2. Через объекты.

 

Последние три главы ориентированы на "мсье извращенцев" и предлагают нам объектный подход к Silverlight. И реализуется он на базе следующего кода:

 

<object data="data:application/x-silverlight," type="application/x-silverlight-2" width="100%" height="100%">
		<param name="source" value="ClientBin/SilverlightApplication1.xap"/>
		<param name="onerror" value="onSilverlightError" />
		<param name="background" value="white" />

		<a href="http://go.microsoft.com/fwlink/?LinkID=108182" style="text-decoration: none;">
 			<img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style: none"/>
		</a>

 

Где xap - это zip-архив с кучкой dll-ок и xaml-файлом. Сделать для него BBCode - раз плюнуть. Вот только вся разница в том, что теперь у клиента будет выполнятся не Javascript, а скомпилированный из .NET, Ruby или иных популярных языков код. Если вы думаете, что этот подход безопаснее предыдущего, то очень глубоко заблуждаетесь.

Изменено пользователем Ritsuka
Ссылка на комментарий
Поделиться на других сайтах

Присоединиться к обсуждению

Вы можете ответить сейчас, а зарегистрироваться позже. Если у вас уже есть аккаунт, войдите, чтобы ответить от своего имени.

Гость
Ответить на вопрос...

×   Вы вставили отформатированный текст.   Удалить форматирование

  Допустимо не более 75 смайлов.

×   Ваша ссылка была автоматически заменена на медиа-контент.   Отображать как ссылку

×   Ваши публикации восстановлены.   Очистить редактор

×   Вы не можете вставить изображения напрямую. Загрузите или вставьте изображения по ссылке.

Зарузка...
×
×
  • Создать...

Важная информация

Находясь на нашем сайте, вы соглашаетесь на использование файлов cookie, а также с нашим положением о конфиденциальности Политика конфиденциальности и пользовательским соглашением Условия использования.