Saving content as PDF from flex had always been a hassle, We know that doing such file operations in AIR is much simpler but due to the file saving ability added in Flash player 10 One can easily save files to the local system.
The next big question is how do i convert my content to PDF format so that it can be correctly saved into the file. Well for that folks at AlivePDF have done a gr8 job and now any one can encode their content into pdf and offer for download. They have a good documentation section which you can read and create more complex stuff.
For beginners i am writing a small example in which i will let the user download a PDF with embedded text or the Image depending on his choice.
<mx:label top="33"left="14"text="Save as PDF Test " fontWeight="bold" fontSize="15"/> <mx:button click="onSaveClicked(event)" label="Save to PDF" id="saveBtn" x="14" y="148"/> <mx:label text="Enter your name:" y="72" x="14"/> <mx:textinput id="myname" x="14" y="90"/> <mx:checkbox id="check" label="Save image" selected="false" x="14" y="121"/> </mx:application>
the Screenshot of the same can be seen below.
Note: please include the AlivePDF swc in your project.
I have just skimmed the surface of the ocean with the above code. but you can write your own brew of concoction that could possibly bring WORLD PEACE :)
The following example demonstrates how you can enable/disable draggable columns in a Flex DataGrid control using the DataGrid class’s draggableColumns property, as well as toggling specific column’s dragability using the DataGridColumn class’s draggable property.
If you want to detect when a data grid column has been reordered, you can listen for the headerShift event on the DataGrid control, as seen in the following example:
The following example shows how you can use the dragEnabled, dropEnabled, and dragMoveEnabled properties with the Flex DataGrid control to copy and move rows between different data grids.
1. blazeds.war 파일 다운로드 이후 Eclipse or Tomcat Import
2. 중요 참조 [jre 5.0 이상에서만 동작함에 유의 !]
blazeds.war 파일을 초기 import 하면 WEB-INF 폴더가 생성됩니다.
WEB-INF └flex └ services-config.xml : 전반적인 서비스 설정을 포함. └ messaging-config.xml : Message Push 서비스 등 메시지 관련 서비스 설정을 포함. └ remoting-config.xml : Remote Object 호출 서비스 설정을 포함. └ proxy-config.xml : 프록시 서비스를 사용할 때 └lib - Flex에서 사용되는 library 파일이 존재하는 폴더 └web.xml - Flex Session Management, MessageBroker Servlet 설정에 대한 내용 포함.
3. services-config.xml
: 기본 채널의 설정 및 포함하는 서비스 파일의 경로를 확인 할 수 있다. my-amf, my-secure-amf, my-polling-amf ..
4. 나머지 .xml 파일
- 설정된 해당 서비스를 확인할 수 있다. - destination id 설정을 통해 flex에서 접근할 수 있도록 설정한다.
ex)
ㄱ. MessagePush : 해당 채널에 대한 종착점 id를 설정한다. < destination id="realMsg"/>
ㄴ. Remote Object : 해당 원격지 클래스를 호출하기 위한 종착점 id를 설정한다. < destination id="fruitRO"> <properties> <source>wonsama.test.FruitManager</source> </properties> < /destination>
5. 기타 확인사항
ㄱ. <default-channels> 하위 노드에 여러개의 채널이 선언된 경우 맨 위쪽 부터 처리하며, 채널이 동작하지 않는 경우 다음 채널 서비스를 실행한다.
<default-channels> <channel ref="my-streaming-amf"/> <!-- 처음 실행됨 --> <channel ref="my-polling-amf"/> <!-- 위 채널이 동작하지 않으면 동작 --> </default-channels>
ㄴ. StreamingAMFChannel 사용 시 <properties>의 하위노드가 1개 이상 존재해야 한다. ==> 존재하지 않으면 Explore에서 정상적으로 MessagePush가 동작하지 않음. (버그인듯?)
The DateFormatter class uses a format String to return a formatted date and time String from an input String or a Date object. The DateFormatter is a very simple formatter. To use it you just have to specify the formatString property, apply the format and you are done. <mx:DateFormatter formatString="Y|M|D|A|E|H|J|K|L|N|S"/> Here are some short explanations of what the characters in formatString represent: Y – Year M – month D – Day A – AM/PM indicator E – day of the week H – Hour (1-24 hours format) J – Hour (0-23 hours format) K – Hour in am/pm (0-11 hours format) L – Hour in am/pm (1-12 hours format) N – Minutes S – Seconds The formatString may also contain other words as separators between Y, M, D, A etc. as we will see in the example below.
Cheng Xiang has a Masters degree in Computer Science and Technology from Tongji University. He works on Java application development at IBM China Development Lab.
Zhang Zhi Hao has a Masters degree in Communication Engineering from Tongji University and has worked with the IBM China Development Lab since 2006. He is interested in RIA and portal development.
Gu Jia has a Masters degree in Computer Science and Technology and joined IBM January 2008. He works on Flex and Java application development at the China Development Lab.
Summary: Adobe® Flex takes you to the next level of Web application development with the concept of Rich Internet Applications (RIAs), while IBM® WebSphere® Portal provides a composite tooling to build flexible, SOA-based solutions. But how do you get the two of them together? One option is to directly integrate Flex into WebSphere Portal server. This article walks you through a process to quickly build rich client and component-based Flex applications for WebSphere Portal, as well as a helpful method to reduce the size of WAR files.
This article is for Flex developers who want to integrate their applications with WebSphere Portal. It assumes that you are familiar with Flex at a basic programming level and that you are familiar with Java™ programming. It also assumes that you have administrative access to a working WebSphere Portal server for the relevant portions of the article. It does not, however, assume that you are familiar with programming or administering WebSphere Portal.
Along with this article, you will need the following tools installed to make sure the sample case works well.
Adobe Flex Builder — This article is written with Adobe Flex Builder 3. Of course, you can do it with the appropriate JDK and a text editor, but the amount of extra work is significant.
WebSphere Portal V6.0.1 or higher — If you are using WebSphere Portal V6.0, you should update your WebSphere Portal V6 environment. (See Resources.)
Let's briefly look at the business requirements of this sample application called TODOList. Many users want to keep records for their appointments, anniversaries, reminders, or any events. And they need to conveniently view their coming items, create new items, and delete any items if possible. Can we provide a smart tool to help them? In this article, we will show you how to build the application in a process that is similar to the way most developers create applications in order to illustrate the complete development procedures.
Figure 1 below shows the sample application infrastructure. We will quickly state the technical aspects of the sample before building the actual application with Adobe Flex and IBM WebSphere Portal. The whole application will be built in a WAR file, including presentation layer and business layer modules, although they are developed in the different projects.
The top rectangle represents a Flex project as the presentation layer that is built by MXML and ActionScript, while the bottom rectangle represents a Java project as the business layer that is built by Java and JDBC. The Flex application calls a Java service through a RemoteObject that is one of the remote procedure call (RPC) components provided by Flex. In this sample application, we will import BlazeDS to implement the remote object.
Adobe Flex is a highly productive, free, open source framework for building and maintaining expressive Web applications that deploy consistently on all major browsers, desktops, and operating systems.
It consists of a rich component library with more than 100 proven, extensible UI components for creating RIAs. It also provides a standard-based language and programming model that supports common design patterns. MXML, a declarative XML-based language, is used to represent UI layout and behaviors, and each MXML file is a separate component. ActionScript, a powerful object-oriented programming language, is used to create client logic. ActionScript provides flow control and object manipulation features that are not available in MXML. Flex 3 was released at the end February 2008, and you can learn more about Flex 3 features from the Adobe Flex Web site. (See Resources.)
Flex applications can be built only by the free Flex SDK, which comprises the Flex framework (component class library) and Flex compiler, enabling you to freely develop and deploy Flex applications using an IDE of your choice. Developers can use Adobe Flex Builder 3 to dramatically accelerate development.
The Flex wizard guides you on how to quickly and easily create this sample in Flex Builder 3.
Open Flex Builder 3, and select File --> New --> Flex Project.
Enter TODOListFlex as the project name.
Select the default location, which is the workspace, as the project location.
Choose Web application as the application type.
For the application server type, you may follow the steps in Adobe Flex 3 Help\Using Flex Builder 3\Flex Builder Basic\Working With Projects if you have a server. But in this sample, we select None, as the Figure 2 screen shot shows, because we don't need that.
Keep all default settings for this Flex application and the build paths in the next two configuration pages.
Click Finish to create this project.
Then, Flex Builder 3 will generate a primary MXML with the same name of new project. This application includes a MXML file, which starts with the <mx:Application> root tag, as follows in Listing 1.
In this section, you only need to care about the main file, TODOListFlex.mxml. You can use the Flex navigator view to import other resources (MXML, ActionScript, and Image) into the project from our sample code. A view of the project category is shown below in Figure 3.
The MXML editor in Flex Builder 3 allows you to work in either Source or Design mode at the top of the editor area. Make sure that you are in Source mode, and then add a <mx:Panel> component as the child of the main application to represent UI layout, and place a <mx:VBox> component in this panel to make it lay in vertical. See Listing 2.
Put a <mx:DataGrid> component between <mx:VBox> tags to list all to-do items. We define an ArrayCollection todoItemColl and assign it as the dataProvider for the DataGrid. (See Listing 3.) We will call RemoteObject service to obtain data for this ArrayCollection in the section, "Use RemoteObject in Flex."
There is a form under the VBox to allow users to add new to-do items. The form contains three text fields (such as Date, Subject, and Owner) and a button. We use a <mx:Grid> component here to control the UI alignment. (See Listing 4.)
Then we create client logic with ActionScript codes within a <mx:Script> tag and wrap the contents in a CDATA construct. (See Listing 5.) To access the different data sources, we define a constant, USE_MOCK_DATA, to control whether the application accesses remote data or local mock data. Now we set the constant value to be true because we are just showing it as a separate application for now. We will elaborate on how to use RemoteObject Service to assess data in the section, "Use RemoteObject in Flex."
<mx:Script>
<![CDATA[
…
private static const USE_MOCK_DATA:Boolean = true; …
private function getTodoList():void
{
if(USE_MOCK_DATA) {
// Creat the mock data
}
else {
// Use remote object to access the back-service
}
}
…
]]>
</mx:Script>
You will find more sample code in the attachment. (See Downloads.) After the above steps, select TODOListFlex.mxml and click the Run button at the toolbar. Flex Builder will compile this application and show the below pages, as in Figure 4.
WebSphere Portal is a framework that lets you plug in new features or extensions called portlets. Portlets are applications within WebSphere Portal, which are the encapsulation of reusable components that combine Web-based content, application functionality, and access to resources.
WebSphere Portal, starting with Version 5.0.2.1, provides a runtime environment for both JSR 168 Portlet API and IBM Portlet API. JSR 168 is a specification from the Java Community Process for the standardization of portlets. The specification was developed to provide interoperability for running portlets on any vendor's implementation of the JSR 168 portlet container. The IBM Portlet API is now deprecated in WebSphere Portal V6.0 in order to show IBM's commitment to the JSR 168 standard portlet API. Also, many new functions will only be available to standard portlets. We will use the JSR 168 standard portlet in our sample.
This section shows how to create a new portlet project using the Rational Software Architecture (RSA) wizard. (See Figure 5.)
Open RSA, and select File --> New --> Project.
Select Portlet Project to create a project.
Enter TODOList as the project name.
Target runtime should be WebSphere Portal V6.0 stub.
Portlet API should be JSR 168 Portlet.
Select the checkbox of "Create a portlet".
Make sure the Basic Portlet is selected as Portlet type.
Actually, you can deploy this portlet on your portal server now. But we will integrate the Flex application created in the previous section into the portlet project first.
The Flex compiler creates SWF files that run in Adobe Flash Player. Flex offers several kinds of compilers: the Web-tier compiler, the mxmlc command-line compiler, and the Flex Builder project compiler. In this article, we will use the Web-tier compiler, which is a set of servlets and servlet filters that run in a J2EE application server. The application server passes on requests from *.mxml files to the servlet container, which then compiles into a SWF file and returns the results to the client. In this case, it allows you to simply copy the Flex files into a directory visible to your server, and the flex codes will be compiled automatically when you request the main application file using your Web browser. This also allows you to rapidly compile, test, and deploy an application instead of compiling your MXML files into a SWF file and then deploying its wrapper files on a Web server.
You should download the FlexModule_J2ER from the Adobe open source Web site if you have not already. Do the following steps to introduce it into this sample portlet project.
Unzip the webtier.war file to a directory called webtier.
Copy flex-bootstrap.jar and flex-bootstrap-jsp.jar from the webtier\WEB-INF\lib to the corresponding WEB-INF\lib directory of the portlet project.
Copy all files and directories from the webtier\WEB-INF\flex directory to the corresponding WEB-INF\flex directory of the portlet project.
Update web.xml file content in the WEB-INF\ directory of the portlet project according to the web.xml file in the webtier\WEB-INF (You can copy the web.xml from the sample code which we have updated accordingly -- see Downloads).
The Flex SDK contains features for accessing server-side data. These components use RPC to interact with server environments to provide data to Flex applications and send data to back-end data sources.
Three kinds of RPC components are supported by Flex: HTTPService, WebService, and RemoteObject. A client-side RPC component calls a remote service and then stores the response data in an ActionScript object where you can easily obtain the data.
We use the RemoteObject component in this sample because it lets you access business logic directly in its native format rather than formatting it as XML, as you do with HTTPService or WebService. This saves you the time required to expose existing logic as XML. The Flex application can access a Java object directly by remote invocation of a method on a designated object. Those objects on the server can then deal with its native data types as arguments, query a database from those arguments, and return its native data types as values.
Another benefit of RemoteObject services is the speed of communication across the wire. Data exchanges still happen over HTTP or HTTPS, but the data itself is serialized into the Action Message Format (AMF), which is a binary format for data serialization/deserialization and remote method invocation. It improves performance by dramatically compressing the size of data transferred and parsing binary data into objects in memory far more efficiently than parsing XML data.
BlazeDS is an Adobe open source project that employs RemoteObject component to access remote Java objects. It contains configurable channels that transport the data between the client and server and can run on a J2EE application server.
You can download the BladeDS package from the Adobe open source Web site. (See Resources.) Do the following steps to enable this portlet application to use BlazeDS:
Unzip the blazeds.war to a directory called blazeds.
Copy all jar files from blazeds\WEB-INF\lib to the WEB-INF\lib directory.
Copy all configuration files from the blazeds\WEB-INF\flex directory to the WEB-INF\flex directory of this application. Overwrite if there are existing ones.
Define MessageBrokerServlet and a session listener in WEB-INF\web.xml of this portlet application, as below in Listing 6. You can skip this step if you copied the web.xml from our sample code.
Copy all files under the src directory from the Flex project to the directory, WebContent/_TODOList/jsp/html. The category of the portlet project should look like Figure 7.
For simplicity, we need only one Java RemoteObject class, TodoItemRO, as the remote business service. You can copy the Java source code and the jdbc.properties file from the sample code (WEB-INF\src) to the portlet project. TodoItem is the only entity Java bean in this sample. (See Figure 8.)
Flex finds the remote services according to its configuration file, services-config.xml, in the WEB-INF\flex. You need to specify the fully qualified class name in the source property of a remoting service destination in the BlazeDS services-config.xml file, or a file that it includes by reference, such as the remoting-config.xml file. The class also must have a no-arg constructor which will be used by Flex to instantiate an instance. We configured the single Java RemoteObject in the remoting-config.xml file which is in WEB-INF\flex, as below in Listing 7.
Now that we have created and configured the remote object, it's time to use it as a remote service.
First, create a RemoteObject component in TODOListFlex.mxml with a unique ID, srvTODOList. The value of the destination should match the destination entry in the WEB-INF\flex\remoting-config.xml file in the portal project. In this sample, it is todoItemRO. (See Listing 8.)
Next, create an AsyncToken object to call the Java method defined in the destination service using the unique ID of the RemoteObject component. The AsyncToken class provides a place to set additional or token-level data for asynchronous RPC operations.
It also allows an IResponder to be attached for an individual call (or, callback method). We define a simple responder class, TokenResponder, that implements the IResponder Interface (see the code sample, TODOListFlex\src\util\TokenResponder.as). It will call the specified callback method when Java returns or raises a specified alert as the handler of any fault. We add it as the responder of the AsyncToken object, get the response data, and transform it into a Flex variable type. (See Listing 9.)
The Flex compiler module for J2EE application servers also provides a JSP tag library that lets you include Flex applications in JSPs. Add the following tag library declaration to your JSP page to import Flex 3 Tag Library in JSP: WebContent\_TODOList\jsp\html\TODOListPortletView.jsp. (See Listing 10.)
Make use of the J2EE Web application archive feature in RSA to export a WAR file so that you can install on a staging or production portal server.
Make sure that the constant USE_MOCK_DATA in the WebContent\_TODOList\jsp\html\TODOListFlex.mxml file has been set to false in order to use RemoteObject to get TODO list. Copy the DB2 JDBC driver jars from sample code to the WEB-INF\lib.
Do the following steps to export the WAR file from this sample project.
Right-click this sample project name and select Export from the pop-up menu.
Select WAR file in the Export window, and then select Next.
Specify a location for the new WAR file.
Click Finish and make sure you can find the WAR file under the location.
Log on to WebSphere Portal Server with the administrator role, and go to the Administrative page to install the WAR file by following these steps.
If it's not already running, start the portal server. From the control panel select Portlet Management , Web Modules.
On the "Manage Web Modules" page, click Install.
On the "Installing a Web module" page, use the Browse button to locate the WAR file. Click Next and Finish. This step may take several minutes due to the large size. You can reduce the size of the WAR using shared lib. (Refer to the section, "Reduce WAR size".)
After installing the portlet, we need to place it into a page. From the Administrative page of the portal server do the following steps.
Navigate to Portal --> User Interface --> Manage Pages.
Locate the page to add a portlet and click Edit Page Layout.
Add the portlet (TODOList) in the page, and click Done to save the changes.
If you host your portal server on a Linux® system (skip this section if you are using a Windows® system), the flash may not be displayed. You may need to configure the java.awt.headless parameter for JVM of portal server as value of true. Follow these steps to do so:
Start the WebSphere Application Server: /opt/IBM/WebSphere/AppServer/bin/startServer.sh server1
Open the WebSphere Application Server Administrative Console: http://server:10001/ibm/console
Navigate to Server --> Application Server --> WebSphere_Portal --> Process Definition --> Java Virtual --> Custom Properties
This step is optional. Because the size of the WAR may be larger than 20MB, you can move some of the contents into the WebSphere Application Service shared lib in order to reduce the size. Refer to the section, "Create a shared library", in the developerWorks article, "Using resource environment providers in WebSphere Application Server". (See Resources.)
This article covered the major features and enhancements during the integration development between Adobe Flex and WebSphere Portal. We also examined the runtime environment used to show the sample application and how easy it can be to create an RIA application and integrate Portal features before delivering the applications for an improved user experience.
Intends to unify all existing Flash Player embed methods and provide a new standard for embedding Adobe Flash Player content
Why should you use SWFObject?
SWFObject 2:
Is more optimized and flexible than any other Flash Player embed method around
Offers one solution for everybody: It shouldn't matter if you are an HTML, Flash, or JavaScript developer, there should be something in it for everyone
Breaks the cycle of being locked into vendor specific markup and promotes the use of web standards and alternative content
Uses unobtrusive JavaScript and JavaScript best practices
SWFObject 2 primarily uses JavaScript to overcome issues that cannot be solved by markup alone; it:
Detects the Flash Player version and determines whether Flash content or alternative content should be shown, to avoid that outdated Flash plug-ins break Flash content
Offers functionality to revert to alternative content in case of an outdated plug-in by means of a DOM manipulation (Note: if no Flash plug-in is installed the HTML object element automatically falls back to its nested alternative content)
Offers the option to use Adobe Express Install to download the latest Flash Player
Offers a JavaScript API to perform common Flash Player and Flash content related tasks
Should I use the static or dynamic publishing method?
SWFObject 2 offers two distinct methods to embed Flash Player content:
The static publishing method embeds both Flash content and alternative content using standards compliant markup, and uses JavaScript to resolve the issues that markup alone cannot solve
The dynamic publishing method is based on marked up alternative content and uses JavaScript to replace this content with Flash content if the minimal Flash Player version is installed and enough JavaScript support is available (similar like previous versions of SWFObject and UFO)
The advantages of the static publishing method are:
The actual authoring of standards compliant markup is promoted
Best embed performance
The mechanism of embedding Flash content does not rely on a scripting language, so your Flash content can reach a significant bigger audience:
If you have the Flash plug-in installed, but have JavaScript disabled or a use a browser that doesn't support JavaScript, you will still be able to see your Flash content
Flash will now also run on a device like Sony PSP, which has very poor JavaScript support
Automated tools like RSS readers are able to pick up Flash content
The advantages of the dynamic publishing method are:
It integrates very well with scripted applications and enables the use of dynamic variables (flashvars)
It avoids click-to-activate mechanisms to activate active content in Internet Explorer 6/7 and Opera 9+. Please note that Microsoft has phased out most active content from its Internet Explorer browsers
How to embed Flash Player content using SWFObject static publishing
STEP 1: Embed both Flash content and alternative content using standards compliant markup
SWFObject's base markup uses the nested-objects method (with proprietary Internet Explorer conditional comments. See Flash Embedding Cage Match) to ensure the most optimal cross-browser support by means of markup only, while being standards compliant and supporting alternative content (See Flash Embed Test Suite):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <htmlxmlns="http://www.w3.org/1999/xhtml"lang="en"xml:lang="en"> <head> <title>SWFObject - step 1</title> <metahttp-equiv="Content-Type"content="text/html; charset=iso-8859-1"/> </head> <body> <div>
NOTE: The nested-objects method requires a double object definition (the outer object targeting Internet Explorer and the inner object targeting all other browsers), so you need to define your object attributes and nested param elements twice.
Required attributes:
classid (outer object element only, value is always clsid:D27CDB6E-AE6D-11cf-96B8-444553540000)
type (inner object element only, value is always application/x-shockwave-flash)
data (inner object element only, defines the URL of a SWF)
width (both object elements, defines the width of a SWF)
height (both object elements, defines the height of a SWF)
Required param element:
movie (outer object element only, defines the URL of a SWF)
NOTE: We advise not to use the codebase attribute to point to the URL of the Flash plugin installer on Adobe's servers, because this is illegal according to the specifications which restrict its access to the domain of the current document only. We recommend the use of alternative content with a subtle message that a user can have a richer experience by downloading the Flash plugin instead.
How can you use HTML to configure your Flash content?
You can add the following often-used optional attributes to the object element:
id
name
class
align
You can use the following optional Flash specific param elements (more info):
The object element allows you to nest alternative content inside of it, which will be displayed if Flash is not installed or supported. This content will also be picked up by search engines, making it a great tool for creating search-engine-friendly content. Summarizing, you should use alternative content when you like to create content that is accessible for people who browse the Web without plugins, create search-engine-friendly content or tell visitors that they can have a richer user experience by downloading the Flash plug-in.
STEP 2: Include the SWFObject JavaScript library in the head of your HTML page
The SWFObject library consists of one external JavaScript file. SWFObject will be executed as soon as it is read and will perform all DOM manipulations as soon as the DOM is loaded - for all browsers that support this, like IE, Firefox, Safari and Opera 9+ - or otherwise as soon as the onload event fires:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <htmlxmlns="http://www.w3.org/1999/xhtml"lang="en"xml:lang="en"> <head> <title>SWFObject - step 2</title> <metahttp-equiv="Content-Type"content="text/html; charset=iso-8859-1"/>
STEP 3: Register your Flash content with the SWFObject library and tell SWFObject what to do with it
First add a unique id to the outer object tag that defines your Flash content. Second add the swfobject.registerObject method:
The first argument (String, required) specifies the id used in the markup.
The second argument (String, required) specifies the Flash player version your content is published for. It activates the Flash version detection for a SWF to determine whether to show Flash content or force alternative content by doing a DOM manipulation. While Flash version numbers normally consist of major.minor.release.build, SWFObject only looks at the first 3 numbers, so both "WIN 9,0,18,0" (IE) or "Shockwave Flash 9 r18" (all other browsers) will translate to "9.0.18". If you only want to test for a major version you can omit the minor and release numbers, like "9" instead of "9.0.0".
The third argument (String, optional) can be used to activate Adobe express install and specifies the URL of your express install SWF file. Express install displays a standardized Flash plugin download dialog instead of your Flash content when the required plugin version is not available. A default expressInstall.swf file is packaged with the project. It also contains the corresponding expressInstall.fla and AS files (in the SRC directory) to let you create your own custom express install experience. Please note that express install will only fire once (the first time that it is invoked), that it is only supported by Flash Player 6.0.65 or higher on Win or Mac platforms, and that it requires a minimal SWF size of 310x137px.
The fourth argument (JavaScript function, optional) can be used to define a callback function that is called on both success or failure of creating a Flash plug-in <object> on the page (see API documentation)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <htmlxmlns="http://www.w3.org/1999/xhtml"lang="en"xml:lang="en"> <head> <title>SWFObject - step 3</title> <metahttp-equiv="Content-Type"content="text/html; charset=iso-8859-1"/> <scripttype="text/javascript"src="swfobject.js"></script>
Just repeat steps 1 and 3 to embed multiple SWF files into one HTML page
The easiest way to reference the active object element is by using the JavaScript API: `swfobject.getObjectById(objectIdStr)
How to embed Flash Player content using SWFObject dynamic publishing
STEP 1: Create alternative content using standards compliant markup
SWFObject's dynamic embed method follows the principle of progressive enhancement and replaces alternative HTML content for Flash content when enough JavaScript and Flash plug-in support is available. First define your alternative content and label it with an id:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <htmlxmlns="http://www.w3.org/1999/xhtml"lang="en"xml:lang="en"> <head> <title>SWFObject dynamic embed - step 1</title> <metahttp-equiv="Content-Type"content="text/html; charset=iso-8859-1"/> </head> <body>
STEP 2: Include the SWFObject JavaScript library in the head of your HTML page
The SWFObject library consists of one external JavaScript file. SWFObject will be executed as soon as it is read and will perform all DOM manipulations as soon as the DOM is loaded - for all browsers that support this, like IE, Firefox, Safari and Opera 9+ - or otherwise as soon as the onload event fires:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <htmlxmlns="http://www.w3.org/1999/xhtml"lang="en"xml:lang="en"> <head> <title>SWFObject dynamic embed - step 2</title> <metahttp-equiv="Content-Type"content="text/html; charset=iso-8859-1"/>
swfobject.embedSWF(swfUrl, id, width, height, version, expressInstallSwfurl, flashvars, params, attributes, callbackFn) has five required and five optional arguments:
swfUrl (String, required) specifies the URL of your SWF
id (String, required) specifies the id of the HTML element (containing your alternative content) you would like to have replaced by your Flash content
width (String, required) specifies the width of your SWF
height (String, required) specifies the height of your SWF
version (String, required) specifies the Flash player version your SWF is published for (format is: "major.minor.release" or "major")
expressInstallSwfurl (String, optional) specifies the URL of your express install SWF and activates Adobe express install. Please note that express install will only fire once (the first time that it is invoked), that it is only supported by Flash Player 6.0.65 or higher on Win or Mac platforms, and that it requires a minimal SWF size of 310x137px.
flashvars (Object, optional) specifies your flashvars with name:value pairs
params (Object, optional) specifies your nested object element params with name:value pairs
attributes (Object, optional) specifies your object's attributes with name:value pairs
callbackFn (JavaScript function, optional) can be used to define a callback function that is called on both success or failure of creating a Flash plug-in <object> on the page (see API documentation)
NOTE: You can omit the optional parameters, as long as you don't break the parameter order. If you don't want to use an optional parameter, but would like to use a following optional parameter, you can simply pass false as its value. For the flashvars, params and attributes JavaScript Objects, you can also pass an empty object instead: {}.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <htmlxmlns="http://www.w3.org/1999/xhtml"lang="en"xml:lang="en"> <head> <title>SWFObject dynamic embed - step 3</title> <metahttp-equiv="Content-Type"content="text/html; charset=iso-8859-1"/> <scripttype="text/javascript"src="swfobject.js"></script>
You can add the following often-used optional attributes to the object element:
id (NOTE: when undefined, the object element automatically inherits the id from the alternative content container element)
align
name
styleclass (see note about class)
class
Note: class is a reserved ECMA4 keyword and will throw errors in Internet Explorer unless it is surrounded by quotation marks (e.g. "class" or 'class'). For this reason, swfobject provides the styleclass keyword as a safe alternative syntax for class; if you use styleclass, swfobject will automatically insert it as class for you.
Example:
var attributes ={ id:"myId", align:"left", styleclass:"myclass" };
If you would rather use class instead of styleclass, wrap the word class in quotes like this:
var attributes ={ id:"myId", align:"left", "class":"myclass" };
You can use the following optional Flash specific param elements (more info):
You can add your name:value pairs while you define an object (note: please make sure not to put a comma behind the last name:value pair inside an object)
<scripttype="text/javascript">
var flashvars ={ name1:"hello", name2:"world", name3:"foobar" }; var params ={ menu:"false" }; var attributes ={ id:"myDynamicContent", name:"myDynamicContent" };
If you don't want to use an optional argument you can define it as false or as an empty Object (NOTE: from SWFObject 2.1 onwards you can also use null or 0):
<scripttype="text/javascript">
var flashvars =false; var params ={}; var attributes ={ id:"myDynamicContent", name:"myDynamicContent" };
The flashvars Object is a shorthand notation that is there for your ease of use. You could potentially ignore it and specify your flashvars via the params Object:
<scripttype="text/javascript">
var flashvars =false; var params ={ menu:"false", flashvars:"name1=hello&name2=world&name3=foobar" }; var attributes ={ id:"myDynamicContent", name:"myDynamicContent" };
Just repeat steps 1 and 3 to embed multiple SWF files into one HTML page
SWFObject 1.5 to SWFObject 2 migration tips
SWFObject 2 is NOT backwards compatible with SWFObject 1.5
It is now preferred to insert all script blocks in the head of your HTML page. Adding your scripts in the body of your page may have visual impact (e.g. flashes of replaced alternative content), because your JavaScript code will be executed in a later stage (the exact impact depends on your implementation)
The library itself is now written in lowercase: swfobject instead of SWFObject
Methods can only be accessed via the library (instead via a SWFObject instance in SWFObject 1.5)
The JavaScript API is entirely different and more elaborate
SWFObject 2 replaces your entire alternative HTML content block, including the referenced HTML container element, for Flash content when enough JavaScript and Flash support is available, while SWFObject 1.5 only replaces the content inside the referenced HTML container. When you don't specify an id attribute, the object element will automatically inherit the id of the HTML container element of your alternative content.
UFO to SWFObject 2 migration tips
SWFObject 2 replaces your entire alternative HTML content block, including the referenced HTML container element, for Flash content when enough JavaScript and Flash support is available, while UFO only replaces the content inside the referenced HTML container. When you don't specify an id attribute, the object element will automatically inherit the id of the HTML container element of your alternative content.
UFO's setcontainercss feature has not been incorporated in SWFObject 2, however it can easily be replicated by using the SWFObject JavaScript API, see: swfobject.createCSS(selStr, declStr)
Does SWFObject 2 support MIME type application/xhtml+xml?
SWFObject 2 does NOT support XML MIME types, which is a design decision.
There are a number of reasons why we are not supporting this:
Only a very small (non-significant) amount of web authors is using it
We are unsure if it is the direction to go. Internet Explorer does not support it and all other major browser vendors are aiming their arrows at a new standard way of HTML parsing (with HTML 5), which departs from the current W3C vision of parsing HTML as XML
We save a considerate amount of file size and effort (testing, issue resolving) by not supporting it
A shell prompt where you can enter commands and interact with the document and the Chrome DevTools. You can evaluate expressions directly in the Console, and can also use the methods provided by the Command Line API, such as $() command for selecting elements, or profile() to start the CPU profiler.
This documentation provides an overview and common uses of these two APIs. You can also browse the Console API and Command Line API reference guides.
Basic operation
Opening the Console
The JavaScript Console is available in two modes within Chrome DevTools: the primary Console tab, or as a split-view you can display while on another tab (such as Elements or Sources).
To open the Console tab, do one of the following:
Use the keyboard shortcut Command - Option - J (Mac) or Control -Shift -J (Windows/Linux).
Select View > Developer > JavaScript Console.
To toggle a split-view of the Console on another tab, press the Esc key on your keyboard, or click the Show/Hide Console button in the bottom left corner of the Chrome DevTools window. In the following screenshot the Console split-view is shown with the Elements panel.
Clearing the console history
To clear the console's history, do one of the following:
Right-click or Ctrl-click anywhere in the Console and choose Clear Console from the context menu that appears.
Enter the clear() Command Line API at the shell prompt.
Use the keyboard shortcut ⌘K or ⌃L (Mac) Control - L (Windows and Linux).
By default, the console history is cleared when you navigate to another page. You can change this behavior by enabling Preserve log upon navigation in the Console area of the Settings dialog (see Console preferences).
Console settings
The Console has two global settings you can modify in the General tab of the DevTools Settings dialog:
Log XMLHTTPRequests—determines if each XMLHTTPRequest is logged to the Console panel.
Preserve log upon navigation—determines if console history for the current page is preserved when you navigate to another page. By default, both of these settings are disabled.
You can also change these settings by right-clicking anywhere in the Console to bring up the context menu.
Using the Console API
The Console API is collection of methods provided by the global console object defined by DevTools. One of the API's main purposes is to log information (such as a property value, or an entire objects or DOM element) to the console while your application is running. You can also group output visually in the console to reduce visual clutter.
Writing to the console
The console.log() method takes one or more expressions as parameters and writes their current values to the console. For example:
var a = document.createElement('p'); a.appendChild(document.createTextNode('foo')); a.appendChild(document.createTextNode('bar')); console.log("Node count: "+ a.childNodes.length);
Instead of concatenating expressions together with the "+" operator (as shown above), you can put each in its own method parameter and they will be joined together in a space-delimited line.
console.log("Node count:", a.childNodes.length,"and the current time is:",Date.now());
Errors and warnings
The console.error() method displays a red icon along with the message text, which is colored red.
function connectToServer(){ console.error("Error: %s (%i)","Server is not responding",500); } connectToServer();
The console.warn() method displays a yellow warning icon with the message text.
if(a.childNodes.length <3){ console.warn('Warning! Too few nodes (%d)', a.childNodes.length); }
Assertions
The console.assert() method conditionally displays an error string (its second parameter) only if its first parameter evaluates to false. For instance, in the following example an error message is written to the console only if the number of child nodes belonging to the list element is greater than 500.
console.assert(list.childNodes.length <500,"Node count is > 500");
Filtering console output
You can quickly filter console output by its severity level--errors, warning, or standard log statements--by selecting one of the filter options along the bottom of the Console, as shown below.
Filter options:
All—Shows all console output.
Errors—Only show output from console.error()
Warnings—Only show output from console.warn()
Logs—Only show output from console.log(), console.info() and console.debug().
Debug—Only show output from console.timeEnd() and other console output.
Grouping output
You can visually group related console output statements together in the console with the console.group() and groupEnd() commands.
var user ="jsmith", authenticated =false; console.group("Authentication phase"); console.log("Authenticating user '%s'", user); // authentication code here... if(!authenticated){ console.log("User '%s' not authenticated.", user) } console.groupEnd();
You can also nest logging groups. In the following example a logging group is created for the authentication phase of a login process. If the user is authenticated, a nested group is created for the authorization phase.
var user ="jsmith", authenticated =true, authorized =true; // Top-level group console.group("Authenticating user '%s'", user); if(authenticated){ console.log("User '%s' was authenticated", user); // Start nested group console.group("Authorizing user '%s'", user); if(authorized){ console.log("User '%s' was authorized.", user); } // End nested group console.groupEnd(); } // End top-level group console.groupEnd(); console.log("A group-less log trace.");
To create a group that is initially collapsed, use console.groupCollapsed() instead of console.group(), as shown below:
console.groupCollapsed("Authenticating user '%s'", user); if(authenticated){ ... }
String substitution and formatting
The first parameter you pass to any of the console's logging methods (log() or error(), for example) may contain one or more format specifiers. A format specifier consists of a % symbol followed by a letter that indicates the formatting that should be applied to the inserted value (%s for strings, for example). The format specifier identifies where to substitute a value provided by a subsequent parameter value.
The following example using the %s (string) and %d (integer) formatters to insert values into the output string.
console.log("%s has %d points","Sam","100");
This would result in "Sam has 100 points" being logged to the console.
The following table lists the supported format specifiers and the formatting they apply:
Format specifier
Description
%s
Formats the value as a string.
%d or %i
Formats the value as an integer.
%f
Formats the object as a floating point value.
%o
Formats the value as an expandable DOM element (as in the Elements panel).
%O
Formats the value as an expandable JavaScript object.
%c
Applies CSS style rules to output string specified by the second parameter.
In the following example the %d format specifier is substituted with the value of document.childNodes.length and formatted as an integer; the %f format specifier is substituted with the value returned by Date.now(), which is formatted as a floating point number.
console.log("Node count: %d, and the time is %f.", document.childNodes.length,Date.now());
Formatting DOM elements as JavaScript objects
By default, when you log a DOM element to the console it's displayed in an XML format, as in the Elements panel:
console.log(document.body.firstElementChild)
You can also log an element's JavaScript representation with the console.dir() method:
console.dir(document.body.firstElementChild);
Equivalently, you can us the %Oformat specifier with console.log():
You use the %c format specifier to apply custom CSS rules to any string you write to the Console with console.log() or related methods.
console.log("%cThis will be formatted with large, blue text","color: blue; font-size:18pt");
Measuring how long something takes
You can use the console.time() and console.timeEnd() methods to measure how long a function or operation in your code takes to complete. You call console.time() at the point in your code where you want to start the timer and console.timeEnd() to stop the timer. The elapsed time between these two calls is displayed in the console.
console.time("Array initialize"); var array=newArray(1000000); for(var i = array.length -1; i >=0; i--){ array[i]=newObject(); }; console.timeEnd("Array initialize");
Marking the Timeline
The Timeline panel gives you a complete overview of where time is spent when loading and using your web app or page. The console.timeStamp() method marks the Timeline at the moment it was executed. This provides an easy way to correlate events in your application with other browser-related events, such as layout or paints.
In the following example the Timeline is marked when the application enters the AddResult() function's implementation.
functionAddResult(name, result){ console.timeStamp("Adding result"); var text = name +': '+ result; var results = document.getElementById("results"); results.innerHTML +=(text +"<br>"); }
As shown in the following screenshot, the timeStamp() command annotates the Timeline in the following places:
A yellow vertical line in the Timeline's summary and detail views.
A record is added to the list of recorded events.
Setting breakpoints in JavaScript
You can start a debugging session from your JavaScript code by calling the debugger command. For instance, in the following example the JavaScript debugger is opened when an object's brightness() function is invoked:
brightness :function(){ debugger; var r =Math.floor(this.red*255); var g =Math.floor(this.green*255); var b =Math.floor(this.blue*255); return(r *77+ g *150+ b *29)>>8; }
Using the Command Line API
In addition to being a place where you can log information from your application, the Console is also a shell prompt where you can directly evaluate expressions or issue commands provided by the Command Line API. This API provides the following features:
Convenience functions for selecting DOM elements
Methods for controlling the CPU profiler
Aliases for a number of Console API methods
Monitoring events
View event listeners registered on objects
Evaluating expressions
The Console attempts to evaluate any JavaScript expression you enter at the shell prompt, upon pressing the Return or Enter key. The Console provides auto-completion and tab-completion. As you type expressions, property names are automatically suggested. If there are multiple properties with the same prefix, pressing the Tab key cycles through them. Pressing the right arrow key accepts the current suggestion. The current suggestion is also accepted by pressing the Tab key if there is only one matched property.
To enter a multi-line expression at the shell prompt (such as a function definition) press Shift+Enter between lines.
Selecting elements
The Command Line API provides several methods to access DOM elements in your application. For example, the $() method returns the first element that matches the specified CSS selector, just like document.querySelector(). For instance, the following code returns the element with the ID "loginBtn".
$('#loginBtn');
The $$() command returns an array of all the elements that match the specified CSS selector, just like document.querySelectorAll(). For instance, the following displays selects all <button> elements with the CSS class "loginBtn":
$$('button.loginBtn');
Lastly, the x() method takes an XPath path as a parameter and returns an array of all elements that match the specified path. The following returns all the <script> elements that are children of the <body> tag:
$x('/html/body/script');
Inspecting DOM elements and JavaScript heap objects
The inspect() method takes a DOM element reference (or JavaScript reference) as a parameter and displays the element or object in the appropriate panel—the Elements panel for DOM elements, or the Profile panel for a JavaScript object.
For example, in the following screenshot the $() function is used to get a reference to an <li> element. Then the last evaluated expression property ($_) is passed to inspect() to open that element in the Elements panel.
Accessing recently selected elements and objects
Often when testing you'll select DOM elements—either directly in the Elements panel or using the Selection tool (magnifying glass)—so that you can further inspect the element. Or, when analyzing a memory snapshot in the Profiles panel, you might select a JavaScript object to further inspect it.
The Console remembers the last five elements (or heap objects) you've selected and makes them available as properties named $0, $1, $2, $3 and $4. The most recently selected element or object is available as $0, the second most as $1, and so forth.
The following screenshot shows the values of these properties after selecting three different elements in turn from the Elements panel:
Monitoring events
The monitorEvents() command monitors an object for one or more specified events. When an event occurs on the monitored object, the corresponding Event object is logged to the Console. You specify the object and the events you want to monitor on that object. For example, the following code enables event monitoring for every "resize" event on the global window object.
monitorEvents(window,"resize");
To monitor several events, you can pass an array of event names as the second parameter. The code below monitors both "mousedown" and "mouseup" events on the body of the document.
You can also pass one of the supported "event types" that DevTools maps to a set of actual event names. For example, the "touch" event type cause DevTools to monitor "touchstart", "touchend", "touchmove", and "touchcancel" events on the target object.
monitorEvents($('#scrollBar'),"touch");
See monitorEvents() in the Console API Reference for a list of supported event types.
To stop monitoring events call unmonitorEvents(), passing the object to stop monitoring.
unmonitorEvents(window);
Controlling the CPU profiler
You can create JavaScript CPU profiles from the command line with the profile() and profileEnd() commands. You can optionally specify a name that's applied to the profile you create.
For example, the following shows an example of creating a new profile with the default name:
The new profile appears in the Profiles panel under the name "Profile 1":
If you specify a label for the new profile, it is used as the new profile's heading. If you create multiple profiles with the same name, they are grouped as individual runs under the same heading: