Beginning with JavaScript--Notes on Basic Knowledge (2)

Posted by maxtech on Sat, 08 Jun 2019 22:52:33 +0200

Windows object

Windows objects not only act as global scopes, but also represent browser window s.

Windows objects have dual roles: they are not only an interface for accessing browser window s through js, but also a Global object specified by ECMAScript.

All variables and functions declared in the global scope become attributes and methods of window s objects. Global variables cannot be deleted by delete operators, but attributes defined directly on Windows objects can.

    var age = 29;
    window.color = "red";

    //Throws an error in IE < 9, returns false in other browsers
    delete window.age;
    //Throws an error in IE < 9, returns true in other browsers
    delete window.color;    //returns true

    alert(window.age);      //29
    alert(window.color);    //undefined
  • Window relationship

Each framework has its own window object and is stored in the framework collection.

<head>
    <title>Frameset Example</title>
</head>
<frameset rows="160,*">
    <frame src="frame.htm" name="topFrame">
    <frameset cols="50%,50%">
        <frame src="anotherframe.htm" name="leftFrame">
        <frame src="yetanotherframe.htm" name="rightFrame">
    </frameset>
</frameset>

Top objects always point to the top-level framework, the browser window. Another window object relative to top is parent. In the absence of a framework, parent must be equal to top

<head>
    <title>Frameset Example</title>
</head>
<frameset rows="100,*">
    <frame src="frame.htm" name="topFrame">
    <frameset cols="50%,50%">
        <frame src="anotherframe.htm" name="leftFrame">
        <frame src="anotherframeset.htm" name="rightFrame">
    </frameset>
</frameset>
  • window position

The screenLeft and screenTop attributes are used to indicate the position of the window relative to the left and top of the screen, respectively.

<body>
    <p>This will open a new window/tab:
    <input type="button" value="Go to Wrox.com" onclick="window.open('http://www.wrox.com/')"></p>
    <p>This will open in the current window/tab:
    <input type="button" value="Go to Wrox.com" onclick="window.open('http://www.wrox.com/', '_self')"></p>
</body>

Using moveTo() and moveBy(), windows can be moved precisely to a new location. Both receive two parameters, moveTo() receives the x and y coordinate values of the new location, and moveBy() receives the number of pixels moving horizontally and vertically.

  • Window size

Windows objects have innerWidth and innerHeight attributes, which can obtain the internal width and height of the browser window. Represents the size of the page view area in the container. The internal width refers to the net width of the web page after removing the space-occupying elements such as menu bar, toolbar, border and so on.

Correspondingly, there is also an outerWidth and outerHeight attribute, which can get the whole width and height of the browser window. Returns the size of the browser window itself.

In Chrome, innerWidth and innerHeight return the same values as outerWidth and outerHeight.

Although the size of the browser window itself cannot be determined, the size of the page viewport can be obtained.

    var pageWidth = window.innerWidth,
        pageHeight = window.innerHeight;

    if (typeof pageWidth != "number"){
        if (document.compatMode == "CSS1Compat"){
            pageWidth = document.documentElement.clientWidth;
            pageHeight = document.documentElement.clientHeight;
        } else {
            pageWidth = document.body.clientWidth;
            pageHeight = document.body.clientHeight;
        }
    }

    alert("Width: " + pageWidth);
    alert("Height: " + pageHeight);

The resizeATo() and resizeBy() methods can be used to adjust the browser window size. Two parameters are received, resizeTo() receives the new width and height of the browser window, and resizeBy() receives the difference between the width and height of the new window and the original window.

  • Navigation and window opening

    Using the window.open() method, you can navigate to a specific URL or open a new browser window. This method can accept four parameters: the URL to be loaded, the window target, a feature string, and a Boolean value indicating whether the new page replaces the current loaded page in the browser history.

    window.open("http://www.baidu.com/", "topFrame")
    // Equivalent to

window.open() returns a reference to the new window and closes the newly opened window by calling the close() method. The newly created window object has an opener property that holds the original window object that opens it.

Setting the opener attribute to null tells the browser that the newly created tab does not need to communicate with the tab that opens it, but can be done in a separate process.

Detecting whether pop-up window is blocked

    var blocked = false;
    try {
        var wroxWin = window.open("http://www.wrox.com", "_blank");
        if (wroxWin == null){
            blocked = true;
        }
    } catch (ex){
        blocked = true;
    }

    if (blocked){
        alert("The popup was blocked!");
    }
  • Intermittent and timeout calls

The timeout call requires the setTimeout() method, which receives two parameters: the code to be executed and the time expressed in milliseconds.

    //Not recommended!
    setTimeout("alert('Hello world!') ", 1000);

    //Recommendation method
    setTimeout(function() { 
        alert("Hello world!"); 
    }, 1000);

As long as clearTimeout() is called before the specified time has passed, the timeout call can be cancelled completely.

    //Setting timeout calls
    var timeoutId = setTimeout(function() {
        alert("Hello world!");
    }, 1000);

    //Note: Cancel it
    clearTimeout(timeoutId);

The timeout call is executed in the global scope, so this value in the function points to the window object in the non-strict mode and undefined in the strict mode.

Intermittent calls: Repeat code execution at specified intervals until cancelled or unloaded. Receive two parameters: the code to be executed and the number of milliseconds to wait before each execution.

    //Not recommended!
    setInterval("alert('Hello world!') ", 10000);

    //Recommendation method
    setInterval(function() { 
        alert("Hello world!"); 
    }, 10000);            

To cancel the batch call that has not yet been executed, you can use the clearInterval() method and pass in the corresponding batch call ID.

    var num = 0;
    var max = 10;
    var intervalId = null;

    function incrementNumber() {
        num++;

        //If the number of executions reaches the value set by max, subsequent calls that have not yet been executed are cancelled
        if (num == max) {
            clearInterval(intervalId);
            alert("Done");
        }
    }

    intervalId = setInterval(incrementNumber, 500);

The variable num is incremented every half second, and the call is cancelled when it reaches its maximum value.

    var num = 0;
    var max = 100;

    function incrementNumber() {
        num++;

        //If the number of executions does not reach the value set by max, set another timeout call
        if (num < max) {
            setTimeout(incrementNumber, 500);
        } else {
            alert("Done");
        }
    }

    setTimeout(incrementNumber, 500);
  • System dialog

The browser uses alert(),confirm(),prompt() methods to call the system dialog box to display messages to users.

  • alert(): Receives a string and displays it to the user.
  • confirm(): In addition to displaying OK, the Cancel Cancel Cancel button is also displayed.
  • prompt(): a prompt box that prompts the user to enter some text. In addition to the OK and Cancel buttons, a text input field is displayed for users to enter content in. Receive two parameters: the text prompt to display to the user and the default value of the text input field.
//Display the Print dialog box
window.print();
//Display the Find dialog box
window.find();

location object

location object is not only the property of window object, but also the property of document object.

Create a function to parse the query string and return an object with all parameters:

    function getQueryStringArgs(){

        //Get the query string and remove the opening question mark
        var qs = (location.search.length > 0 ? location.search.substring(1) : ""),

            //Objects that hold data
            args = {},

            //Get each item
            items = qs.length ? qs.split("&") : [],
            item = null,
            name = null,
            value = null,

            //Use in for loop
            i = 0,
            len = items.length;

        //Add each item to the args object one by one
        for (i=0; i < len; i++){
            item = items[i].split("=");
            name = decodeURIComponent(item[0]);
            value = decodeURIComponent(item[1]);

            if (name.length){
                args[name] = value;
            }
        }

        return args;
    }

    //Suppose the string of the query is? Q = javascript & num = 10

    var args = getQueryStringArgs();

    alert(args["q"]);     //"javascript"
    alert(args["num"]);   //"10"

Using location objects can change the location of browsers in many ways.

  • location.assign("http://www.baidu.com");
  • window.location="http://www.baidu.com";
  • location.href="http://www.baidu.com";

You can change the URL by setting hash,search,hostname,pathname,port attributes to new values. After these modifications, the browser's history will generate a new record, and the user can navigate to the previous interface by clicking Back. To disable this behavior, use the replace() method, which receives a parameter: the URL to navigate to, and the result does not generate a new record in the history.

reload(): reload the currently displayed page. To force a reload from the server, the following methods are used:

location.reload();//It is possible to load from the cache
location.reload(true);//Reload from server

You can get it with location.href. To get the value of each part of the URL, you can write as follows:

location.protocol; // 'http'
location.host; // 'www.example.com'
location.port; // '8080'
location.pathname; // '/path/index.html'
location.search; // '?a=1&b=2'
location.hash; // 'TOP'

To load a new page, you can call location.assign(). If you want to reload the current page, it's very convenient to call the location.reload() method.

navigator object

navigator objects represent browser information. The most commonly used attributes include:

  • navigator.appName: Browser name;
  • navigator.appVersion: Browser version;
  • navigator.language: The language set by the browser;
  • navigator.platform: Operating system type;
  • navigator.userAgent: User-Agent string set by browser.

    //Detection plug-in (invalid in IE)
    function hasPlugin(name){
        name = name.toLowerCase();
        for (var i=0; i < navigator.mimeTypes.length; i++){
            if (navigator.mimeTypes[i].name.toLowerCase().indexOf(name) > -1){
                return true;
            }
        }
    
        return false;
    }
    
    //flash detection
    alert(hasPlugin("Flash"));
    
    //Detection of quicktime
    alert(hasPlugin("QuickTime"));
    
    //detect Java
    alert(hasPlugin("Java"));
    

In this example hasPlugin() receives a parameter: the name of the plug-in to be detected.

    //Detecting plug-ins in IE
    function hasIEPlugin(name){
        try {
            new ActiveXObject(name);
            return true;
        } catch (ex){
            return false;
        }
    }

    //flash detection
    alert(hasIEPlugin("ShockwaveFlash.ShockwaveFlash"));

    //Detection of quicktime
    alert(hasIEPlugin("QuickTime.QuickTime"));

In this example, hasIEPlugin() receives only one COM identifier as a parameter.

    //plugin detection - doesn't work in IE
    function hasPlugin(name){
        name = name.toLowerCase();
        for (var i=0; i < navigator.plugins.length; i++){
            if (navigator.plugins[i].name.toLowerCase().indexOf(name) > -1){
                return true;
            }
        }

        return false;
    }        

    //plugin detection for IE
    function hasIEPlugin(name){
        try {
            new ActiveXObject(name);
            return true;
        } catch (ex){
            return false;
        }
    }

    //detect flash for all browsers
    function hasFlash(){
        var result = hasPlugin("Flash");
        if (!result){
            result = hasIEPlugin("ShockwaveFlash.ShockwaveFlash");
        }
        return result;
    }

    //detect quicktime for all browsers
    function hasQuickTime(){
        var result = hasPlugin("QuickTime");
        if (!result){
            result = hasIEPlugin("QuickTime.QuickTime");
        }
        return result;
    }

    //detect flash
    alert(hasFlash());

    //detect quicktime
    alert(hasQuickTime());

Note that navigator information can be easily modified by users, so the values read by JavaScript are not necessarily correct. Many beginners like to use if to judge the browser version in order to write different code for different browsers, for example:

var width;
if (getIEVersion(navigator.userAgent) < 9) {
    width = document.body.clientWidth;
} else {
    width = window.innerWidth;
}

But this may not only be inaccurate judgment, but also difficult to maintain the code. The correct way is to make full use of the undefined feature of JavaScript for non-existent attributes, and calculate directly with the short-circuit operator | | ________.

var width = window.innerWidth || document.body.clientWidth;    

history object

The history object keeps the browser's history. JavaScript can call back() or forward() of the history object, which is equivalent to the user clicking the browser's "back" or "forward" button.
The go() method can be used to jump arbitrarily in the user's history, either backward or forward.

history.go(-1);//Back one page
history.go(1);//Forward page
history.back();//Back one page
history.forword();//Forward page

Topics: Windows IE Javascript Attribute