Chrome扩展如何获取当前浏览器窗口所在屏幕的显示尺寸信息
Chrome扩展获取当前窗口所在屏幕参数的实现方案
你需要结合两个Chrome扩展API配合实现,之前只用到了chrome.system.display,遗漏了获取当前浏览器窗口坐标的API调用,具体实现步骤如下:
第一步:manifest.json 权限声明
首先要在扩展的清单文件中加入两个必备权限:
{ "manifest_version": 3, "name": "屏幕参数获取工具", "version": "1.0", "permissions": ["system.display", "windows"], "action": {} }
第二步:核心实现逻辑
逻辑思路是先拿到当前浏览器窗口的坐标,再匹配到对应屏幕的信息:
- 调用
chrome.windows.getCurrent获取当前激活的Chrome窗口的位置坐标(left、top属性) - 调用
chrome.system.display.getInfo获取所有已连接显示器的参数,每个显示器的bounds属性记录了该屏幕在全局显示坐标系中的位置和尺寸 - 遍历所有显示器,判断当前窗口的左上角坐标落在哪个显示器的坐标范围内,该显示器就是你需要的目标屏幕
以下是可直接使用的示例代码:
// 点击扩展图标时触发逻辑 chrome.action.onClicked.addListener(async () => { // 1. 获取当前激活窗口的信息 const currentWindow = await chrome.windows.getCurrent(); const windowLeft = currentWindow.left; const windowTop = currentWindow.top; // 2. 获取所有已连接显示器的参数 const allDisplays = await chrome.system.display.getInfo(); // 3. 匹配当前窗口所在的显示器 const targetDisplay = allDisplays.find(display => { const bounds = display.bounds; // 判断窗口左上角是否处于当前显示器的坐标范围内 return windowLeft >= bounds.left && windowLeft < bounds.left + bounds.width && windowTop >= bounds.top && windowTop < bounds.top + bounds.height; }); // 输出目标屏幕的分辨率参数 if (targetDisplay) { console.log('当前屏幕分辨率:', `${targetDisplay.bounds.width} * ${targetDisplay.bounds.height}`); // 也可以直接取官方提供的分辨率属性:targetDisplay.resolution.width / height } });
补充说明
如果窗口跨屏显示,上述逻辑会以窗口左上角所在的屏幕为准;如果你需要以窗口占比更大的屏幕为准,可以额外计算窗口和每个屏幕的重叠面积,取面积最大的那一个即可。
内容的提问来源于stack exchange,提问作者Dinesh Patil
相关产品推荐
相关产品推荐

