自学内容网 自学内容网

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');
      }
    }
  );
});


原文地址:https://blog.csdn.net/weixin_42152604/article/details/142781750

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!