阿里云主机折上折
  • 微信号
Current Site:Index > The core API of the window object

The core API of the window object

Author:Chuan Chen 阅读数:22393人阅读 分类: JavaScript

The window object is the global object in the browser environment, representing the current browser window or tab. It provides a vast array of properties and methods for controlling the browser window, manipulating documents, handling events, and interacting with the browser. Understanding the core APIs of the window object is crucial for building dynamic web pages.

Basic Properties of the window Object

The window object contains many useful properties that provide direct access to browser window information or global variables.

// Get the width and height of the window
console.log(window.innerWidth);  // Viewport width
console.log(window.innerHeight); // Viewport height

// Get screen information
console.log(window.screen.width);   // Screen width
console.log(window.screen.height);  // Screen height

The window object also provides navigation-related properties:

// Get the current page's URL
console.log(window.location.href);

// Get browser information
console.log(window.navigator.userAgent);

Methods of the window Object

The window object offers many practical methods for controlling the browser window and performing various operations.

Popup Methods

// Display an alert box
window.alert('This is a warning');

// Display a confirmation dialog
const isConfirmed = window.confirm('Are you sure you want to delete?');
if (isConfirmed) {
    console.log('User confirmed the action');
}

// Display an input dialog
const userName = window.prompt('Please enter your name', 'Anonymous');
console.log(`Username: ${userName}`);

Timer Methods

Timers are one of the most commonly used features of the window object:

// Set a one-time timer
const timeoutId = window.setTimeout(() => {
    console.log('This code will execute after 3 seconds');
}, 3000);

// Clear the timer
window.clearTimeout(timeoutId);

// Set an interval timer
const intervalId = window.setInterval(() => {
    console.log('This code executes every 2 seconds');
}, 2000);

// Clear the interval timer
window.clearInterval(intervalId);

Window Operations

The window object allows developers to control browser window behavior:

// Open a new window
const newWindow = window.open('https://example.com', '_blank', 'width=600,height=400');

// Close the window
newWindow.close();

// Resize the window
window.resizeTo(800, 600);

// Move the window
window.moveTo(100, 100);

Event Handling

The window object can listen to various browser events:

// Listen for window resize events
window.addEventListener('resize', () => {
    console.log(`Window size changed: ${window.innerWidth}x${window.innerHeight}`);
});

// Listen for scroll events
window.addEventListener('scroll', () => {
    console.log(`Current scroll position: ${window.scrollY}`);
});

// Listen for page load completion
window.addEventListener('load', () => {
    console.log('Page and all resources have finished loading');
});

Storage APIs

The window object provides client-side storage solutions:

// Use localStorage
window.localStorage.setItem('theme', 'dark');
const theme = window.localStorage.getItem('theme');
console.log(theme); // Output: dark

// Use sessionStorage
window.sessionStorage.setItem('token', 'abc123');
const token = window.sessionStorage.getItem('token');
console.log(token); // Output: abc123

History Management

The window.history object allows manipulation of the browser's history:

// Move forward one page
window.history.forward();

// Move back one page
window.history.back();

// Jump to a specific position in history
window.history.go(-2); // Move back two pages

// Add a new history entry
window.history.pushState({page: 1}, "title 1", "?page=1");

// Replace the current history entry
window.history.replaceState({page: 2}, "title 2", "?page=2");

Request Animation Frame

window.requestAnimationFrame is an important API for animation development:

function animate() {
    const element = document.getElementById('box');
    let position = 0;
    
    function step() {
        position += 1;
        element.style.left = position + 'px';
        
        if (position < 200) {
            window.requestAnimationFrame(step);
        }
    }
    
    window.requestAnimationFrame(step);
}

animate();

Cross-Window Communication

The window object supports communication between different windows or iframes:

// Parent window sends a message
const iframe = document.getElementById('myFrame');
iframe.contentWindow.postMessage('Hello from parent', 'https://example.com');

// Child window receives the message
window.addEventListener('message', (event) => {
    if (event.origin !== 'https://parent.com') return;
    console.log('Message received:', event.data);
});

Performance Measurement

window.performance provides data related to page performance:

// Measure code execution time
window.performance.mark('start');

// Perform some operations
for (let i = 0; i < 1000000; i++) {
    Math.sqrt(i);
}

window.performance.mark('end');
window.performance.measure('My Operation', 'start', 'end');

const measures = window.performance.getEntriesByName('My Operation');
console.log(measures[0].duration); // Output operation duration (milliseconds)

Global Object Characteristics

As a global object, window has some special behaviors:

// Global variables are actually properties of window
var globalVar = 'I am a global variable';
console.log(window.globalVar); // Output: I am a global variable

// Function declarations also become methods of window
function globalFunc() {
    console.log('I am a global function');
}
window.globalFunc(); // Output: I am a global function

// Variables declared with let/const do not become window properties
let localVar = 'I am a local variable';
console.log(window.localVar); // Output: undefined

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

上一篇:DOM性能优化

下一篇:location对象操作

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.