You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Chrome扩展Manifest v3内容脚本如何获取屏幕完整坐标?

解决Chrome扩展Manifest V3中获取屏幕完整像素尺寸的问题

在Chrome环境下,内容脚本无法直接通过screen对象获取屏幕的完整位置与尺寸,但可以借助Chrome官方提供的chrome.system.display API实现需求,具体步骤如下:

1. 配置Manifest权限

首先在manifest.json中声明system.display和windows权限,这两个API需要显式授权才能使用:

{
  "manifest_version": 3,
  "permissions": ["system.display", "windows"],
  "background": {
    "service_worker": "service-worker.js"
  },
  // 其他扩展配置项...
}

2. 通过消息传递实现跨上下文获取数据

由于内容脚本无法直接调用chrome.system.display API,需要通过消息传递机制,让后台脚本(Service Worker)代为获取屏幕信息,再将结果返回给内容脚本:

后台脚本(service-worker.js)

// 监听来自内容脚本的请求
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.type === 'getFullScreenInfo') {
    // 获取所有显示器的完整信息
    chrome.system.display.getInfo((displays) => {
      // 获取当前窗口的位置,用于匹配对应的显示器
      chrome.windows.getCurrent({ populate: false }, (currentWindow) => {
        const winX = currentWindow.left;
        const winY = currentWindow.top;
        // 筛选出当前窗口所在的显示器
        const targetScreen = displays.find(screen => {
          const screenBounds = screen.bounds;
          return winX >= screenBounds.left && winX < screenBounds.left + screenBounds.width &&
                 winY >= screenBounds.top && winY < screenBounds.top + screenBounds.height;
        });
        if (targetScreen) {
          // 返回屏幕的完整位置与尺寸(bounds为完整区域,不含系统占用的可用区域是workArea)
          sendResponse({
            left: targetScreen.bounds.left,
            top: targetScreen.bounds.top,
            width: targetScreen.bounds.width,
            height: targetScreen.bounds.height
          });
        } else {
          sendResponse(null);
        }
      });
    });
    // 标记为异步响应
    return true;
  }
});

内容脚本

// 向后台发送请求获取屏幕完整信息
chrome.runtime.sendMessage({ type: 'getFullScreenInfo' }, (screenInfo) => {
  if (screenInfo) {
    console.log('屏幕完整参数:', screenInfo);
    // 在这里使用拿到的left/top/width/height做后续处理
  } else {
    console.error('无法获取目标屏幕信息');
  }
});

核心说明

  • chrome.system.display.getInfo()返回的每个显示器对象中,bounds属性对应屏幕的完整像素范围(包含任务栏、dock等系统占用区域),完全符合你需要的完整尺寸与左上角坐标需求;
  • 多显示器场景下,通过当前窗口的位置匹配对应显示器,确保拿到的是窗口所在屏幕的准确数据。

内容的提问来源于stack exchange,提问作者Bri Bri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 16:46:03