chrome extension创建新的window

背景

  • 在接收一段代码的时候遇到问题,创建的新的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');
      }
    }
  );
});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值