Chrome扩展Service Worker中右键菜单点击时获取屏幕尺寸方法
在Chrome扩展Service Worker中实现居中弹出对话框的方案
由于Service Worker属于无DOM环境,无法直接访问screen对象,我们可以通过Chrome扩展提供的chrome.system.displayAPI获取屏幕尺寸,结合chrome.windows.create实现居中弹窗,无需向网页注入脚本。具体步骤如下:
1. 配置Manifest权限
在manifest.json中添加所需权限,确保Service Worker能调用相关API:
{ "manifest_version": 3, "name": "你的扩展名称", "version": "1.0", "permissions": ["contextMenus", "system.display", "windows"], "background": { "service_worker": "background.js" } }
2. Service Worker中的实现代码
在background.js中完成右键菜单注册、屏幕尺寸获取和弹窗创建:
// 安装扩展时注册右键菜单 chrome.runtime.onInstalled.addListener(() => { chrome.contextMenus.create({ id: 'show-select-popup', title: '打开选择对话框', contexts: ['page'] // 右键触发范围为页面任意区域 }); }); // 监听右键菜单点击事件 chrome.contextMenus.onClicked.addListener(async (info) => { if (info.menuItemId === 'show-select-popup') { await showSelectPopUp(); } }); // 实现居中弹窗逻辑 async function showSelectPopUp() { const popupWidth = 420; const popupHeight = 600; // 获取所有显示器信息,优先取主显示器 const displays = await chrome.system.display.getInfo(); const mainDisplay = displays.find(d => d.isPrimary) || displays[0]; const { width: screenWidth, height: screenHeight } = mainDisplay.bounds; // 计算居中位置 const left = Math.round((screenWidth / 2) - (popupWidth / 2)); const top = Math.round((screenHeight / 2) - (popupHeight / 2)); // 创建居中弹窗 chrome.windows.create({ url: 'src/selector/selector.html', type: 'popup', width: popupWidth, height: popupHeight, left: left, top: top, focused: true // 弹窗创建后自动获得焦点 }); }
关键说明
chrome.system.display.getInfo():返回所有显示器的详细信息,包括屏幕尺寸、工作区范围等,我们通过isPrimary筛选主显示器,确保弹窗在主屏幕居中。- 无需注入脚本:整个逻辑完全在Service Worker中完成,不会对网页DOM产生任何影响。
- 兼容性:该方案基于Manifest V3,适配最新版Chrome浏览器。
内容的提问来源于stack exchange,提问作者jack chen
相关产品推荐
相关产品推荐

