其他BOM对象

Navigator对象

navigator对象提供浏览器和系统信息。

基本属性

// 浏览器信息
console.log(navigator.userAgent);      // 用户代理字符串
console.log(navigator.appName);        // 浏览器名称
console.log(navigator.appVersion);     // 浏览器版本
console.log(navigator.platform);       // 操作系统平台
console.log(navigator.language);       // 浏览器语言
console.log(navigator.languages);      // 语言列表
console.log(navigator.cookieEnabled);  // Cookie是否启用
console.log(navigator.onLine);         // 是否在线
console.log(navigator.vendor);         // 浏览器厂商

硬件信息

// 硬件并发数(CPU核心数)
console.log(navigator.hardwareConcurrency);

// 设备内存(GB)
console.log(navigator.deviceMemory);

// 最大触摸点
console.log(navigator.maxTouchPoints);

// 屏幕方向
console.log(navigator.screenOrientation);

连接信息

// 网络连接信息
if (navigator.connection) {
    const connection = navigator.connection;
    
    console.log(connection.effectiveType);  // "4g", "3g", "2g", "slow-2g"
    console.log(connection.downlink);       // 下行速度(Mbps)
    console.log(connection.rtt);            // 往返时间(ms)
    console.log(connection.saveData);       // 是否启用省流模式
    
    // 监听网络变化
    connection.addEventListener("change", function() {
        console.log("网络状态变化:", connection.effectiveType);
    });
}

地理位置

// 获取地理位置
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
        function(position) {
            console.log("纬度:", position.coords.latitude);
            console.log("经度:", position.coords.longitude);
            console.log("精度:", position.coords.accuracy);
        },
        function(error) {
            console.error("获取位置失败:", error.message);
        },
        {
            enableHighAccuracy: true,
            timeout: 5000,
            maximumAge: 0
        }
    );
    
    // 持续监听位置
    const watchId = navigator.geolocation.watchPosition(
        function(position) {
            console.log("位置更新:", position.coords);
        }
    );
    
    // 停止监听
    navigator.geolocation.clearWatch(watchId);
}

剪贴板API

// 异步剪贴板API
async function copyText(text) {
    try {
        await navigator.clipboard.writeText(text);
        console.log("复制成功");
    } catch (err) {
        console.error("复制失败:", err);
    }
}

async function pasteText() {
    try {
        const text = await navigator.clipboard.readText();
        console.log("粘贴内容:", text);
        return text;
    } catch (err) {
        console.error("粘贴失败:", err);
    }
}

// 复制图片
async function copyImage(blob) {
    try {
        await navigator.clipboard.write([
            new ClipboardItem({ "image/png": blob })
        ]);
    } catch (err) {
        console.error("复制失败:", err);
    }
}

其他实用方法

// 注册Service Worker
if ("serviceWorker" in navigator) {
    navigator.serviceWorker.register("/sw.js")
        .then(registration => {
            console.log("注册成功:", registration);
        })
        .catch(error => {
            console.error("注册失败:", error);
        });
}

// 发送信标(页面卸载时也能发送)
navigator.sendBeacon("/analytics", JSON.stringify({
    page: location.pathname,
    time: Date.now()
}));

// 分享API
if (navigator.share) {
    navigator.share({
        title: "东巴文",
        text: "学习编程的好地方",
        url: "https://db-w.cn"
    })
    .then(() => console.log("分享成功"))
    .catch(err => console.error("分享失败:", err));
}

// 电池状态
if (navigator.getBattery) {
    navigator.getBattery().then(battery => {
        console.log("电量:", battery.level * 100 + "%");
        console.log("是否充电:", battery.charging);
    });
}

Screen对象

screen对象提供屏幕信息。

基本属性

// 屏幕尺寸
console.log(screen.width);      // 屏幕宽度
console.log(screen.height);     // 屏幕高度
console.log(screen.availWidth); // 可用宽度(排除任务栏)
console.log(screen.availHeight);// 可用高度

// 颜色深度
console.log(screen.colorDepth); // 颜色深度(位)
console.log(screen.pixelDepth); // 像素深度(位)

// 方向
console.log(screen.orientation.type);  // "portrait-primary" 或 "landscape-primary"

屏幕信息应用

// 检测屏幕尺寸
function getScreenType() {
    const width = screen.width;
    
    if (width < 768) return "mobile";
    if (width < 1024) return "tablet";
    return "desktop";
}

// 检测高DPI屏幕
function isHighDPI() {
    return window.devicePixelRatio > 1;
}

// 检测Retina屏幕
function isRetina() {
    return window.devicePixelRatio >= 2;
}

// 获取实际像素尺寸
function getActualDimensions() {
    return {
        width: screen.width * window.devicePixelRatio,
        height: screen.height * window.devicePixelRatio
    };
}

全屏API

const element = document.documentElement;

// 进入全屏
function enterFullscreen() {
    if (element.requestFullscreen) {
        element.requestFullscreen();
    } else if (element.webkitRequestFullscreen) {
        element.webkitRequestFullscreen();
    } else if (element.msRequestFullscreen) {
        element.msRequestFullscreen();
    }
}

// 退出全屏
function exitFullscreen() {
    if (document.exitFullscreen) {
        document.exitFullscreen();
    } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen();
    } else if (document.msExitFullscreen) {
        document.msExitFullscreen();
    }
}

// 切换全屏
function toggleFullscreen() {
    if (!document.fullscreenElement) {
        enterFullscreen();
    } else {
        exitFullscreen();
    }
}

// 监听全屏变化
document.addEventListener("fullscreenchange", function() {
    if (document.fullscreenElement) {
        console.log("进入全屏");
    } else {
        console.log("退出全屏");
    }
});

用户代理检测

解析userAgent字符串获取浏览器信息。

基本检测

const ua = navigator.userAgent;

// 检测浏览器
function detectBrowser() {
    if (ua.indexOf("Chrome") > -1) return "Chrome";
    if (ua.indexOf("Safari") > -1) return "Safari";
    if (ua.indexOf("Firefox") > -1) return "Firefox";
    if (ua.indexOf("Edge") > -1) return "Edge";
    if (ua.indexOf("MSIE") > -1 || ua.indexOf("Trident") > -1) return "IE";
    return "Unknown";
}

// 检测移动设备
function isMobile() {
    return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(ua);
}

// 检测iOS
function isIOS() {
    return /iPad|iPhone|iPod/.test(ua);
}

// 检测Android
function isAndroid() {
    return /Android/.test(ua);
}

// 检测微信
function isWeChat() {
    return /MicroMessenger/i.test(ua);
}

特性检测(推荐)

// 不推荐:浏览器检测
if (detectBrowser() === "Chrome") {
    // Chrome特定代码
}

// 推荐:特性检测
if ("geolocation" in navigator) {
    navigator.geolocation.getCurrentPosition(...);
}

if ("serviceWorker" in navigator) {
    navigator.serviceWorker.register(...);
}

if (window.Promise && window.fetch) {
    // 使用Promise和fetch
}

浏览器检测

更精确的浏览器检测方法。

现代浏览器检测

// 检测浏览器引擎
function detectEngine() {
    const ua = navigator.userAgent;
    
    if (ua.indexOf("Gecko") > -1 && ua.indexOf("KHTML") === -1) {
        return "Gecko";  // Firefox
    }
    if (ua.indexOf("AppleWebKit") > -1) {
        return "WebKit"; // Chrome, Safari
    }
    if (ua.indexOf("Trident") > -1) {
        return "Trident"; // IE
    }
    if (ua.indexOf("Edge") > -1) {
        return "EdgeHTML"; // 旧Edge
    }
    return "Unknown";
}

// 检测浏览器版本
function getChromeVersion() {
    const match = navigator.userAgent.match(/Chrome\/(\d+)/);
    return match ? parseInt(match[1]) : null;
}

function getFirefoxVersion() {
    const match = navigator.userAgent.match(/Firefox\/(\d+)/);
    return match ? parseInt(match[1]) : null;
}

function getSafariVersion() {
    const match = navigator.userAgent.match(/Version\/(\d+).*Safari/);
    return match ? parseInt(match[1]) : null;
}

浏览器能力检测

// 检测ES6支持
const hasES6 = (function() {
    try {
        new Function("(a = 0) => a");
        return true;
    } catch (e) {
        return false;
    }
})();

// 检测async/await
const hasAsyncAwait = (function() {
    try {
        new Function("(async () => {})()");
        return true;
    } catch (e) {
        return false;
    }
})();

// 检测可选链
const hasOptionalChaining = (function() {
    try {
        eval("const a = {}; a?.b");
        return true;
    } catch (e) {
        return false;
    }
})();

设备检测

检测设备类型和特性。

设备类型检测

// 检测设备类型
function getDeviceType() {
    const ua = navigator.userAgent;
    
    if (/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(ua)) {
        return "tablet";
    }
    if (/Mobile|Android|iP(hone|od)|IEMobile|BlackBerry|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(ua)) {
        return "mobile";
    }
    return "desktop";
}

// 检测触摸设备
function isTouchDevice() {
    return (
        "ontouchstart" in window ||
        navigator.maxTouchPoints > 0 ||
        navigator.msMaxTouchPoints > 0
    );
}

// 检测平板
function isTablet() {
    return /(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(navigator.userAgent);
}

// 检测手机
function isPhone() {
    return /Mobile|Android|iP(hone|od)|IEMobile|BlackBerry|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(navigator.userAgent);
}

设备能力检测

// 检测摄像头
async function hasCamera() {
    try {
        const devices = await navigator.mediaDevices.enumerateDevices();
        return devices.some(device => device.kind === "videoinput");
    } catch (e) {
        return false;
    }
}

// 检测麦克风
async function hasMicrophone() {
    try {
        const devices = await navigator.mediaDevices.enumerateDevices();
        return devices.some(device => device.kind === "audioinput");
    } catch (e) {
        return false;
    }
}

// 检测蓝牙
function hasBluetooth() {
    return "bluetooth" in navigator;
}

// 检测USB
function hasUSB() {
    return "usb" in navigator;
}

// 检测NFC
function hasNFC() {
    return "nfc" in navigator;
}

响应式检测

// 使用媒体查询检测
function matchMedia(query) {
    return window.matchMedia(query).matches;
}

// 检测屏幕方向
function getOrientation() {
    return matchMedia("(orientation: portrait)") ? "portrait" : "landscape";
}

// 检测暗色模式
function isDarkMode() {
    return matchMedia("(prefers-color-scheme: dark)");
}

// 检测减少动画偏好
function prefersReducedMotion() {
    return matchMedia("(prefers-reduced-motion: reduce)");
}

// 检测打印样式
function isPrintMedia() {
    return matchMedia("print");
}

// 监听媒体查询变化
const darkModeQuery = window.matchMedia("(prefers-color-scheme: dark)");
darkModeQuery.addEventListener("change", function(e) {
    if (e.matches) {
        document.body.classList.add("dark");
    } else {
        document.body.classList.remove("dark");
    }
});

下一步

掌握了其他BOM对象后,让我们继续学习:

  1. 客户端存储 - 学习Cookie和Storage
  2. 回调函数 - 学习异步编程基础
  3. Promise - 学习Promise异步处理

东巴文(db-w.cn) - 让编程学习更简单

🎯 东巴文寄语:Navigator和Screen对象提供了丰富的设备和浏览器信息,但要注意特性检测优于浏览器检测的原则。在 db-w.cn,我们帮你掌握现代Web API的使用!