Javascript 简明教程

JavaScript - Browsers Compatibility

为了以预期的方式处理每个浏览器,重要的是了解不同浏览器之间的差异。因此,了解您的网页正在哪个浏览器中运行非常重要。

It is important to understand the differences between different browsers in order to handle each in the way it is expected. So it is important to know which browser your web page is running in.

用内置 navigator 对象获取您的网页当前正在运行的浏览器信息。

To get information about the browser your webpage is currently running in, use the built-in navigator object.

Navigator Properties

有一些与 Navigator 相关的属性,您可以在您的网页中使用。以下是每个属性的名称和说明。

There are several Navigator related properties that you can use in your Web page. The following is a list of the names and descriptions of each.

Navigator Methods

有一些特定的 Navigator 方法。以下是它们名称和说明的列表。

There are several Navigator-specific methods. Here is a list of their names and descriptions.

Browser Detection

有一个简单的 JavaScript,它可以用来找出浏览器的名称,然后可以向用户提供相应 HTML 页面。

There is a simple JavaScript which can be used to find out the name of a browser and then accordingly an HTML page can be served to the user.

<html>
   <head>
      <title>Browser Detection Example</title>
   </head>

   <body>
      <script type = "text/javascript">
         var userAgent   = navigator.userAgent;
         var opera       = (userAgent.indexOf('Opera') != -1);
         var ie          = (userAgent.indexOf('MSIE') != -1);
         var gecko       = (userAgent.indexOf('Gecko') != -1);
         var netscape    = (userAgent.indexOf('Mozilla') != -1);
         var version     = navigator.appVersion;

         if (opera) {
            document.write("Opera based browser");
            // Keep your opera specific URL here.
         } else if (gecko) {
            document.write("Mozilla based browser");
            // Keep your gecko specific URL here.
         } else if (ie) {
            document.write("IE based browser");
            // Keep your IE specific URL here.
         } else if (netscape) {
            document.write("Netscape based browser");
            // Keep your Netscape specific URL here.
         } else {
            document.write("Unknown browser");
         }

         // You can include version to along with any above condition.
         document.write("<br /> Browser version info : " + version );
      </script>
   </body>
</html>

Output

执行以上程序后,你会得到类似以下的输出−

On executing the above program, you will get the output similar to the following −

请注意,根据你使用的浏览器类型,你可能会得到更多有关浏览器的信息。

Please note that you may get some more information about the browser depending upon the type of browser you are using.