JavaScript Browser Programming

Source: Internet
Author: User
Tags access properties

Not only are JavaScript object-based, but browsers are also made up of objects. When JavaScript is running in a browser, it can access the browser's objects in the same way as the built-in objects that use JavaScript. The browser provides a number of objects, such as the window object corresponding to the browser, the Document object corresponds to the browser's page, and so on. There are many other objects that represent the HTML written on the page, for example, each element corresponds to an IMG object that inserts an image into the document.

The collection of objects that the browser provides for JavaScript is often referred to as the browser object model (Browser object Model,bom). There is a potential drawback to these additional features of javascript: There is no standard way to implement a BOM. Which object collection can be used is highly dependent on the type and version of the browser currently in use. If you use only the core functionality of the BOM (objects that all browsers have), the code will work better in different browsers and versions.

Introduction to Browser objects

When JavaScript runs in a page, it can access a large number of other objects provided by the Web browser. Similar to the Math object, these objects are created automatically and do not need to be displayed to create them. Objects and their methods, properties, and events are mapped in the BOM.
Objects commonly used in the BOM. In a way, these parts of the BOM are common to all browsers.

The BOM has a hierarchical structure. At the top of the hierarchy is the Window object, which represents the browser's frame and all its related content, such as scroll bars and navigation bar icons. The page is included in the window frame. In the BOM, the page is represented by the Document object.

WinDOS Object

The WinDOS object represents the browser's frame or window, which contains the page. In a way, the object also represents the browser itself, which contains a number of attributes. For example, by WinDOS the properties of an object, you can determine what browser is running, what pages the user has visited, the size of the browser window, and the size of the user's screen. You can also use the Window object to access or modify the text in the browser's status bar, modify the loaded page, or even open a new window.
The Window object is a global object, so you do not need to use its name to access properties and methods. In fact, global functions and global variables, which can be accessed anywhere in the page, are created as properties of the global object.
Some properties of the Window object are also objects. Common objects for all browsers include Document,navigator,history,screen and location. The Document object represents a page; The History object contains historical information about the user's access to the page; The Navigator object contains information about the browser; The screen object is information about the display capability of the hamburger client; The Location object contains the position information of the current page.

Note: The function name or variable name used in the Web page cannot conflict with the BOM object and its properties and method names. Because any function or variable defined in the global scope will actually be added to the Window object.
For example

var myVariable="hello world!";alert(window.myVariable);

The message "Hello World" will be displayed in the warning box.

History Object

The History object tracks each page that the user accesses. This page list is often called the browser's history stack. It allows the user to click the back or Forward button of the browser to revisit the page. The history object can be accessed through the History property of the Window object.
The history object has the length property. Use it to get the number of pages in the history stack. The history object has the back () and forward () methods. When they are called, the page location that the browser is currently loading becomes the previous page or page that the user visited. The Go () method of the History object, with a parameter that specifies how many pages to forward or rewind in the historical stack.
Note: Go (-1) is equivalent to back (), and Go (1) is equivalent to forward ().

Location Object

The Location object contains a lot of useful information about the current page position. It contains not only the unified resource locator for the page (Uniform Resource locator,url), but also the server that holds the page, the port number of the connection server, and the protocol used. This information is available through the Href,hostname,port and protocol properties of the location object. However, this information is related to where the page is accessed: whether the page is loaded from the server or the page is loaded directly from the local hard disk.
In addition to getting the current page position, you can use the Location object's method to change the current page position or refresh the current page. You can navigate to another page in two ways. One is to set the HREF property of the Location object to point to another page, and the second is to use the Replace () method of the Location object. Both of these methods have the same effect, and the page changes position. The difference, however, is that the replace () method removes the current page from the history stack and replaces it with a new page, while using the HREF attribute only adds the new page to the top of the history stack.

For example, to replace the current page with a new page mypage.html, the code for using the Replace () method is as follows:

location.replace("myPage.html");

If you want to load a new page and add it to the top of the history stack, you can use the href attribute:

location.href="myPage.html";
Navigator Object

The Navigator object is a property of the Window object that can be used for all browsers. The more appropriate name for this object is "browser object", because the Navigator object contains a lot of information about the browser and the operating system running the browser.
The most common use of Navigator objects is to handle differences between browsers. Using its properties, you can determine the user's browser, browser version, and operating system. This information can then be manipulated to ensure that the code runs only in the browser that supports it. This technology has become "browser sniffing", which has some limitations. An alternative to browser sniffing is "feature detection," a technique that detects whether a browser supports a particular feature.
The AppName and UserAgent properties of the Navigator object are useful for identifying browsers. The AppName property returns the browser's model, such as Microsoft Internet Explorer to IE, and returns Netscape to Firefox,chrome and Safari. The UserAgent property returns a string containing multiple pieces of information, such as the version of the browser, the operating system, and the browser model. The return of this property varies by browser, such as getting the useragent string in Chrome:

<body>    <script>        function  getBrowserMsg() {            var ua=navigator.userAgent;            document.writeln(ua);        }        getBrowserMsg();    </script>

The page output is:
mozilla/5.0 (Windows NT 10.0; WOW64) applewebkit/537.36 (khtml, like Gecko) chrome/54.0.2840.87 safari/537.36

  • Geolocation Object
    The Geolocation property has been added to the Navigator object in the HTML5 specification. The primary role is to allow developers to obtain and utilize the location of devices and computers. The user must give developer permissions to obtain and use this information. For example:
  • The core part of the Geolocation object is its GetCurrentPosition method. When the method is called, a callback function must be passed to it, and the callback function executes after the GetCurrentPosition method's work is completed successfully.

            function getSuccess(position) {            var coords=position.coords;            var latitude=coords.latitude;            var longitude=coords.longitude;            var message="You‘re at "+latitude+" , "+longitude;            document.write(message+"<br>");        }

    For example, the Getsuccess function is the callback function that executes when navigator.geolocation.getCurrentPosition determines the location of the computer or device. The parameter position of the Getsuccess function is an object that contains the earthly location and the elevation of the computer or device, which can be obtained by position the Coords property of the object. Latitude represents the dimension of the computer, longitude represents the longitude of the computer, the altitude represents the altitude, and the speed property is used to get the device/computer.

            function  getError(errorObj) {            document.write(errorObj.message+"<br>");        }        navigator.geolocation.getCurrentPosition(getSuccess,getError);

    The second parameter of the GetCurrentPosition () method is another callback function that executes when an error occurs. The error callback function has only one parameter, which indicates the reason why the GetCurrentPosition method failed to run. It is an object that contains two attributes. The first property, code, is a numeric value that represents the reason for the failure.

    value Description
    1 page does not have permission to get the location of the device/computer
    2 An internal error has occurred
    3 The time allowed before acquiring the location of the device/computer has reached

    The second property is a message that represents human-readable information that describes the error.

    Screen Object

    The screen object properties of the Window object contain a large amount of information about the client's ability to display. Its properties include height and width, respectively, representing the vertical and horizontal dimensions of the screen, in pixels. The screen object also has the ColorDepth property, which represents the number of color bits used by the client screens. To determine how many colors are on the screen, you only need to calculate the colordepth of 2. For example, ColorDepth is 1, which means there are only two colors, while colordepth is 8, which means 256 colors. Most screens now have a color depth of at least 8, usually 24 or 32.

    Document Object

    As with the Window object, the Document object may be one of the most important and commonly used objects in the BOM. With this object, you can access the HTML elements on the page and their properties and methods.
    The Document object has many properties associated with it, and they are also similar to arrays of structures, called collections. The main collections are forms,images and links. IE also supports many other collection properties, such as the All collection property, which is an array of all the elements represented on the page by the object.

  • Images Collection
    You can insert an image in an HTML page using a tag:
  • <img alt="USA" name="myImage" src="usa.gif">

    The browser creates an IMG object MyImage, which allows the image to be manipulated by JavaScript. In fact, each image on the page has a corresponding IMG object. Each IMG object on the page is saved in the images collection, which is a property of the Document object. The use of this collection and other collections is the same as for arrays. The first picture on the page is in the document.images[0] element, the second image is in document.images[1], and so on.
    The IMG object has many very useful properties. The most important of these is the SRC attribute, which changes it to change the loaded image.

  • Links collection
    For each hyperlink element < A/> that has an href attribute, the browser creates an A object. The most important attribute of a object is the href, which is the href attribute that should be tagged. Using this property, you can determine where the link is pointing, and you can modify it after the page is loaded. A collection of all the A objects on the page is contained in the collection of links.
  • JavaScript Browser Programming

    Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.