1. Trang chủ
  2. » Công Nghệ Thông Tin

Beginning JavaScript Third Edition phần 9 potx

79 326 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 79
Dung lượng 1,34 MB

Nội dung

if (navigator.plugins[plugInCounter].name.indexOf(“RealPlayer”) >= 0) { plugInInstalled = true; break; } } } else { if (real1.readyState == 4) { plugInInstalled = true; } } if (plugInInstalled == false) { window.location.replace(“NoRealPlayerPage.htm”); } } </script> </head> <body onload=”return window_onload()”> <noembed> <h2>This Page requires a browser supporting Plug-ins or ActiveX controls</h2> </noembed> </body> </html> In the window_onload() function, you first define a variable, plugInInstalled, and initialize it to false. Next, since checking for plug-ins or controls is browser-dependent, you check to see if this is a Microsoft browser. If not, you assume it’s Firefox, though for a real-life example you might want to do more detailed checks. If the browser is Firefox, you use a for loop to go through the navigator object’s plugins array, check- ing each installed plug-in’s name for the word RealPlayer. If this word is found, you set the variable plugInInstalled to true and break out of the for loop. If you find that this is a Microsoft browser, you use the readyState property of the <object/> ele- ment’s Object object to see if the ActiveX control is loaded, initialized successfully, and now ready for action. If its value is 4, you know that all systems are ready to go, and you can use the control, so you set the variable plugInInstalled to true. Finally, the last if statement in the function checks to see if plugInInstalled is true or false. If it is false, the user is redirected to another page, called NoRealPlayerPage.htm, where you can either provide alternative ways to display the content or provide a link to load the RealPlayer control. Let’s cre- ate a simple page to do this. <html> <head> <title>No Real Player Installed</title> </head> 609 Chapter 15: Using ActiveX and Plug-Ins with JavaScript 18_051511 ch15.qxp 4/13/07 6:24 PM Page 609 <body> <h2>You don’t have the required RealPlayer plug-in</h2> <p> You can download the plug-in from <a href=”http://www.real.com”>Real Player</a> </p> </body> </html> Save this as NoRealPlayerPage.htm. Finally, back in the realplayer.htm page, let’s enable the user to select a sound file as well as to start and stop playing it. You add the following code to the top of the script block: <html> <head> <object classid=”clsid:CFCDAA03-8BE4-11CF-B84B-0020AFBBCCFA” id=”real1” width=”0” height=”0”> <param name=”height” value=”0”> <param name=”width” value=”0”> <embed name=”real1” id=”real1” border=”0” controls=”play” height=0 width=0 type=”audio/x-pn-realaudio-plugin”> </object> <script type=”text/javascript”> var fileName = “”; function butPlay_onclick() { document.real1.SetSource(“file:///” + fileName); document.real1.DoPlay(); } function butStop_onclick() { document.real1.DoStop(); } function file1_onblur() { fileName = document.form1.file1.value; } function window_onload() { var plugInInstalled = false; if (navigator.appName.indexOf(“Microsoft”) == -1) { var plugInCounter; for (plugInCounter = 0; plugInCounter < navigator.plugins.length; 610 Chapter 15: Using ActiveX and Plug-Ins with JavaScript 18_051511 ch15.qxp 4/13/07 6:24 PM Page 610 plugInCounter++) { if (navigator.plugins[plugInCounter].name.indexOf(“RealPlayer”) >= 0) { plugInInstalled = true; break; } } } else { if (real1.readyState == 4) { plugInInstalled = true; } } if (plugInInstalled == false) { window.location.replace(“NoRealPlayerPage.htm”); } } </script> </head> <body onload=”return window_onload()”> <noembed> <h2>This Page requires a browser supporting Plug-ins or ActiveX controls</h2> </noembed> </body> </html> You also add a form with buttons for starting, stopping, and choosing a sound file to the body of the page. <html> <head> <object classid=”clsid:CFCDAA03-8BE4-11CF-B84B-0020AFBBCCFA” id=”real1” width=”0” height=”0”> <param name=”height” value=”0”> <param name=”width” value=”0”> <embed name=”real1” id=”real1” border=”0” controls=”play” height=0 width=0 type=”audio/x-pn-realaudio-plugin”> </object> <script type=”text/javascript”> var fileName = “”; function butPlay_onclick() { document.real1.SetSource(“file:///” + fileName); document.real1.DoPlay(); } function butStop_onclick() 611 Chapter 15: Using ActiveX and Plug-Ins with JavaScript 18_051511 ch15.qxp 4/13/07 6:24 PM Page 611 { document.real1.DoStop(); } function file1_onblur() { fileName = document.form1.file1.value; } function window_onload() { var plugInInstalled = false; if (navigator.appName.indexOf(“Microsoft”) == -1) { var plugInCounter; for (plugInCounter = 0; plugInCounter < navigator.plugins.length; plugInCounter++) { if (navigator.plugins[plugInCounter].name.indexOf(“RealPlayer”) >= 0) { plugInInstalled = true; break; } } } else { if (real1.readyState == 4) { plugInInstalled = true; } } if (plugInInstalled == false) { window.location.replace(“NoRealPlayerPage.htm”); } } </script> </head> <body onload=”return window_onload()”> <noembed> <h2>This Page requires a browser supporting Plug-ins or ActiveX controls</h2> </noembed> <form id=form1 name=form1> <input type=”button” value=”Play Sound” id=”butPlay” name=”butPlay” onclick=”return butPlay_onclick()”> <input type=”button” value=”Stop Sound” id=”butStop” name=”butStop” onclick=”return butStop_onclick()”> <input type=”file” id=”file1” name=”file1” onblur=”return file1_onblur()”> </form> </body> </html> 612 Chapter 15: Using ActiveX and Plug-Ins with JavaScript 18_051511 ch15.qxp 4/13/07 6:24 PM Page 612 You’ve completed your page, so let’s now resave it. Load realplayer.htm into your browser and, as long as your browser supports plug-ins or ActiveX controls and the RealPlayer plug-in is installed, you should see something like what is shown in Figure 15-9. Figure 15-9 Click the Browse button and browse to an MP3 sound file ( Budd_Eno.mp3 is provided with the code download, or you can create your own with Real Producer Basic, also available at www.realnetworks .com ). Click the Play Sound and Stop Sound buttons to play and stop the sound. So how does this work? The form in the body of the page contains three form elements. The first two of these are just standard buttons, but the last is an <input/> element of type=”file”. This means that a text box and a button are displayed. When the button is clicked, a Choose File dialog box opens, enabling you to choose the .ra file you want to hear. When chosen, this file’s name appears in the text box. You’ve connected the two buttons’ onclick event handlers and the file control’s onblur event handler to three functions, butPlay_onclick(), butStop_onclick(), and file1_onblur(), respectively, which are defined in the script block in the head of the page. In the function file1_onblur(), you set a global variable, fileName, to the value of the file control. In other words, fileName will contain the name and path of the file the user has chosen to play. The blur event will fire whenever the user moves focus from the file control to another control or area of the page. In reality, you would perform checks to see whether the file type selected by the user is actually a valid sound file. In the other two functions, you access the RealPlayer plug-in or control that you embedded in the page. You use one function to load the file the user selected and play it, and the other function to stop play. In both functions, you access the RealPlayer control by using its name prefixed with document. The script will work with IE and Firefox, though under IE it’s accessing the ActiveX control defined in <object/>, and in Firefox it’s accessing the plug-in defined in the <embed/> tag. In the butPlay_onclick() function, you use the SetSource() method of the RealPlayer object. This method takes one parameter — the file that you want the RealPlayer plug-in to load. So, in the line document.real1.SetSource(“file:///” + fileName); 613 Chapter 15: Using ActiveX and Plug-Ins with JavaScript 18_051511 ch15.qxp 4/13/07 6:24 PM Page 613 you load the file the user specified. Next you use the DoPlay() method of the RealPlayer object, which starts the playing of the source file. document.real1.DoPlay(); With the function butStop_onclick(), you stop the playing of the clip using the DoStop() method of the RealPlayer object. document.real1.DoStop(); Testing Your “No Plug-in or ActiveX Control” Redirection Script It’s quite likely that if you plan to use an ActiveX control or plug-in, you’re going to make sure it’s installed on your computer. The problem is that while that’s great for testing pages to see if they work when there is a control installed, it does make it very difficult to check redirection scripts for users with- out that control. You have a number of possible options: 1. Get a second computer with a clean install of an operating system and browser, then load your pages on that computer. This is the only 100 percent sure way of checking your pages. 2. Uninstall the plug-in. Depending on how the plug-in or control was installed, there may be an uninstall program for it. Windows users can use the Add/Remove programs option in the Control Panel. 3. For Firefox, install a different version of the browser. For example, if you have Firefox 2 installed, try installing an older version, say Firefox 1 or even a beta version if you can find it. The plug-ins currently installed are not normally available to a browser installed later, though this may not be true all the time. 4. With IE, you can only have one version of the browser installed at once. However, IE does make it quite easy to remove ActiveX controls. In IE 5+, choose Internet Options from the Tools menu. Click the Settings button under Temporary Internet Files (Browsing History in IE7), followed by the View Objects button. From here you need to right-click the name of the control you want removed and select Remove from the pop-up menu. Potential Problems Plug-ins and ActiveX controls provide a great way to extend a browser’s functionality, but they do so at a price — compatibility problems. Some of the problems you may face are discussed in the following sections. Similar but Not the Same — Differences Between Browsers Although a plug-in for Firefox and the equivalent ActiveX control for IE may support many similar properties and methods, you will often find significant, and sometimes subtle, differences. For example, both the plug-in and ActiveX control versions of RealPlayer support the SetSource() method. However, while document.real1.SetSource(“file:///D:\\MyDir\\MyFile.ra”) 614 Chapter 15: Using ActiveX and Plug-Ins with JavaScript 18_051511 ch15.qxp 4/13/07 6:24 PM Page 614 will work with IE, it will cause problems with the other browsers. To work with Firefox and the like, specify the protocol by which the file will be loaded. If it is a URL, specify http://, but for a file on a user’s local hard drive, use file:///. To make the code work across platforms, you must type this: document.real1.SetSource(“file:///D:\MyDir\MyFile.ra”) Differences in the Scripting of Plug-ins When scripting the RealPlayer plug-in for Firefox, you embedded it like this: <embed name=”real1” id=”real1” border=”0” controls=”play” height=0 width=0 type=”audio/x-pn-realaudio-plugin”> You then accessed it via script just by typing this: document.real1.DoPlay() However, if you are scripting a Flash player, you need to add the following attribute to the <embed/> definition in the HTML: swliveconnect=”true” Otherwise any attempts to access the plug-in will result in errors. <embed name=”map” swLiveConnect=true src=”topmenu.swf” width=300 height=200 pluginspage=”http://fpdownload.macromedia.com/get/shockwave/cabs/flash/swflash.cab” Version=ShockwaveFlash”> It’s very important to study any available documentation that comes with a plug-in to check that there are no subtle problems like this. Differences Between Operating Systems Support for ActiveX controls varies greatly between different operating systems. IE for the Mac supports it, but not as well as under Win32 operating systems, such as Windows 95, 98, 2000, and XP. You also need to be aware that an ActiveX control written for Win32 will not work on the Mac; you need to make sure a Mac-specific control is downloaded. IE on the Mac supports plug-ins as well as ActiveX controls; so, for example, Flash is a plug-in on the Mac and an ActiveX control on Win32. Clearly, if you want to support both Mac and Windows users, you need to write more complex code. It’s very important to check which operating system the user is running (for example, using the scripts given at the end of Chapter 5) and deal with any problems that may arise. 615 Chapter 15: Using ActiveX and Plug-Ins with JavaScript 18_051511 ch15.qxp 4/13/07 6:24 PM Page 615 Differences Between Different Versions of the Same Plug-in or ActiveX Control Creators of plug-ins and controls will often periodically release new versions with new features. If you make use of these new features, you need to make sure not only that the user has the right plug-in or ActiveX control loaded, but also that it is the right version. ActiveX Controls With ActiveX controls, you can add version information in the codebase attribute of the <object/> element. <object classid=clsid:AAA03-8BE4-11CF-B84B-0020AFBBCCFA id=”myControl” codebase=”http://myserver/mycontrol.cab#version=3,0,0,0”> </object> Now, not only will the browser check that the control is installed on the user’s system, but it’ll also check that the installed version is version 3 or greater. What if you want to check the version and then redirect to a different page if it’s a version that is earlier than your page requires? With ActiveX controls there’s no easy way of using JavaScript code to check the ActiveX control version. One way is to find a property that the new control supports but that older versions don’t, and then com- pare that to null. For example, imagine you have a control whose latest version introduces the property BgColor. To check if the installed version is the one you want, you type the following: if (document.myControl.BgColor == null) { alert(“This is an old version”); } It’s also possible that the ActiveX creator has added to his control’s object a version property of some sort that you can check against, but this will vary from control to control. Plug-ins With plug-ins you need to make use of the Plugin objects in the navigator object’s plugins[] array property. Each Plugin object in the array has a name, filename, and description property, which may provide version information. However, this will vary between plug-ins. For example, for Flash Player 4 on Win32, the description given by navigator.plugins[“Shockwave Flash”].description is Flash 4.0 r7. Using regular expressions, which were introduced in Chapter 8, you could extract the version number from this string: 616 Chapter 15: Using ActiveX and Plug-Ins with JavaScript 18_051511 ch15.qxp 4/13/07 6:24 PM Page 616 var myRegExp = /\d{1,}.\d{1,}/; var flashVersion = navigator.plugins[“Shockwave Flash”].description; flashVersion = parseFloat(flashVersion.match(myRegExp)[0]); In the first line of code you define a regular expression that will match one or more digits, followed by a dot, and then one or more numbers. Next you store the description of the Flash plug-in in the variable flashVersion. Finally you search the variable for the regular expression, returning an array of all the matches made. You then use the parseFloat() function on the contents of the element in the array at index 0 (in other words, the first element in the array). Changes to Internet Explorer 6 Service Pack 1b and ActiveX Controls For mostly legal reasons, Microsoft is making changes to how ActiveX controls work in IE. Now when- ever a user browses to a page with an ActiveX control, she gets a warning about the control, and by default it’s blocked unless she chooses to unblock it. There are two ways around this: 1. Don’t access any external data or have any <param/> elements in the definition, as the follow- ing example demonstrates: <object classid=”CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6”></object> 2. Use the new noexternaldata attribute to specify that no external access of data is used. <object noexternaldata=”true” classid=”CLSid:6BF52A52-394A-11d3-B153-00C04F79FAA6”> <param name=”URL” value=”http://msdn.microsoft.com/workshop/samples/author/dhtml/media/drums.wav”/> </object> The URL parameter will be ignored, and no external data from the URL, in this case a .wav file, will be accessed. Summary In this chapter you looked at how you can use plug-ins and ActiveX controls to extend a browser’s func- tionality. You saw that: ❑ Internet Explorer supports ActiveX controls, and to some extent plug-ins, on Windows operat- ing systems. Firefox has good support for plug-ins but does not support ActiveX controls. ❑ Most creators of plug-ins also provide an ActiveX control equivalent. Internet Explorer and Firefox are incompatible as far as the installation of plug-ins and ActiveX controls goes. ❑ Plug-ins are embedded in a web page by means of the <embed/> element. You let Firefox know which plug-in is to be embedded by specifying either a source file or a MIME type using the src and type attributes of the <embed/> element. If you define a value for the <embed/> element’s pluginspage attribute, users who don’t have that plug-in installed will be able to click a link and install it. ❑ You can find detailed information about what plug-ins are installed on your Firefox browser, as well as their descriptions and types, by using the About Plug-ins option on the Help menu. 617 Chapter 15: Using ActiveX and Plug-Ins with JavaScript 18_051511 ch15.qxp 4/13/07 6:24 PM Page 617 ❑ To use script to check if a user has a certain plug-in, you can use the navigator object’s plug- ins[] array property. For each plug-in installed, there will be a Plugin object defined in this array. Each Plugin object has the properties name, description, filename, and length, which you can use to determine if a plug-in exists on the user’s computer. You can also use the navigator object’s mimeTypes[] array property to check if a certain type of file is supported. ❑ Internet Explorer supports ActiveX controls as an alternative to plug-ins. These are embedded into a web page using the <object/> element. You specify which ActiveX control you want by using the classid attribute. If you want to have controls automatically install for users who don’t have a particular control already installed, you need to specify the codebase attribute. ❑ Any parameters particular to the control are specified by means of the <param/> element, which is inserted between the opening and closing <object> tags. ❑ You can check whether a control has loaded successfully using the readyState property of the Object object, which returns a number: 0 if the control is not installed, 1 if it’s still loading, 2 if it has loaded, 3 if you can interact with it, and 4 if it’s installed and ready for use. ❑ Virtually every different type of plug-in and ActiveX control has its own interface, for which the control’s documentation will provide the details. You looked briefly at the RealPlayer control by RealNetworks. ❑ You also saw that while plug-ins and controls are great for extending functionality, they are sub- ject to potential pitfalls. These include differences in the way plug-ins and ActiveX controls are scripted, differences in operating systems, and differences between versions of the same plug-in or control. In the next chapter, you change direction to cover a “new” JavaScript technique that has rekindled web application development. Exercise Question A suggested solution to this question can be found in Appendix A. Question 1 Using the RealPlayer plug-in/ActiveX control, create a page with three links, so that when the mouse pointer rolls over any of them a sound is played. The page should work in Firefox and IE. However, any other browsers should be able to view the page and roll over the links without errors appearing. 618 Chapter 15: Using ActiveX and Plug-Ins with JavaScript 18_051511 ch15.qxp 4/13/07 6:24 PM Page 618 [...]... username for the Username field and email for the Email field This enables you to easily find the elements and get the text entered into them The third column contains an element The hyperlinks use the javascript: protocol to call JavaScript code In this case, the checkUsername() and checkEmail() functions are called when the user clicks the links We’ll examine these functions in a few... making only portions of the page reload with new data The term “remote scripting” is quite large in scope, as a variety of JavaScript techniques can be used These techniques incorporate the use of hidden frames/iframes, dynamically adding elements to the document, and/or using JavaScript to send HTTP requests to the server; the latter has become quite popular in the last couple of years These... the browser that runs the web application, and like every other advanced JavaScript concept we’ve covered in this book, Ajax capabilities differ from browser to browser Thankfully, the most common forms of Ajax work in the following browsers: 621 Chapter 16: Ajax and Remote Scripting ❑ Internet Explorer 5+ ❑ Firefox 1+ ❑ Opera 9+ ❑ Safari 2+ When using hidden frames, a popular Ajax approach, with these... chapter) However, when you start using other forms of Ajax, the differences in code become apparent Ajax with JavaScript: The XMLHttpRequest Object As stated before, there are a variety of ways that you can create Ajax-enabled applications However, probably the most popular Ajax technique is using the JavaScript XMLHttpRequest object, which is present in IE 5+, Firefox, Opera, and Safari Despite its name,... can be either GET or POST The second argument is the URL to send the request to, and the third is a true or false value indicating whether the request should be made in asynchronous mode We discussed synchronous and asynchronous modes in Chapter 14, but as a refresher, requests made in synchronous mode halt all JavaScript code from executing until a response is received from the server The next step... for show in this example Verifying a typed password is certainly something the server application can do; however, it is far more efficient to let JavaScript perform that verification Next to the Username and Email fields will be a hyperlink that calls a JavaScript function to query the server with the HttpRequest class you built earlier in this chapter The server application is a simple PHP file PHP... following: Form Field Validation fieldname { text-align: right; } submit { text-align: right; } function checkUsername() { var userValue = document.getElementById(“username”).value; if (userValue == “”) { alert(“Please enter a user name to check!”); return;... Username: 637 Chapter 16: Ajax and Remote Scripting Check Availability Email: Check Availability Password: JavaScript, and its remote scripting ability What Is Remote Scripting? Essentially, remote scripting allows client-side JavaScript to request and receive data from a server without refreshing the web page This technique enables the developer to create an application . Player Installed</title> </head> 6 09 Chapter 15: Using ActiveX and Plug-Ins with JavaScript 18_051511 ch15.qxp 4/13/07 6:24 PM Page 6 09 <body> <h2>You don’t have the required. RealPlayer plug-in is installed, you should see something like what is shown in Figure 15 -9. Figure 15 -9 Click the Browse button and browse to an MP3 sound file ( Budd_Eno.mp3 is provided with. IE for the Mac supports it, but not as well as under Win32 operating systems, such as Windows 95 , 98 , 2000, and XP. You also need to be aware that an ActiveX control written for Win32 will not

Ngày đăng: 09/08/2014, 14:21