背景
- 在接收一段代码的时候遇到问题,创建的新的window窗口怎么都出不来,而且background对应代码在创建window完成之后获取的tab报错,并且控制台明确窗口没展示出来(有的电脑可以,有的电脑不行)。

解决方案
- 必须写全width\height\left\top,否则在某些电脑上面正常,在某些电脑上面不正常,和分辨率强相关,目前没找到规律
chrome.windows.create(
{
type: 'normal',
url: chrome.runtime.getURL('content.html'),
width: 1000,
height: 800,
left: 100,
top: 100
},
(e) => {
console.log(e)
chrome.tabs.update(e.tabs[0].id, { pinned: true })
// chrome.tabs.update(e.id, { pinned: true })
}
)
最优解决方案
- 采用用户屏幕大小自动计算的方式
- 未采纳,因为需要增加system权限,会导致插件更新的时候用户的插件自动关闭,减少用户
chrome.system.display.getInfo((displays) => {
// 获取主屏幕的宽度和高度
const screenWidth = displays[0].workArea.width;
const screenHeight = displays[0].workArea.height;
// 确保窗口不会超出屏幕的50%
const windowWidth = Math.min(1000, screenWidth - 100); // 让窗口宽度不超过屏幕宽度
const windowHeight = Math.min(800, screenHeight - 100); // 让窗口高度不超过屏幕高度
chrome.windows.create(
{
type: 'normal',
url: chrome.runtime.getURL('content.html'),
width: windowWidth,
height: windowHeight,
left: Math.max(0, (screenWidth - windowWidth) / 2), // 居中或者不超出屏幕
top: Math.max(0, (screenHeight - windowHeight) / 2), // 居中或者不超出屏幕
},
(e) => {
console.log(e);
if (e.tabs && e.tabs.length > 0) {
chrome.tabs.update(e.tabs[0].id, { pinned: true });
} else {
console.error('No tabs found in the created window');
}
}
);
});