微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

事件处理程序中的错误:ReferenceError: window is not defined chrome extension with manifest v3

如何解决事件处理程序中的错误:ReferenceError: window is not defined chrome extension with manifest v3

我正在将清单版本 3 用于 chrome 扩展,这个错误我在后台 js 中遇到: 事件处理程序中的错误:ReferenceError: window is not defined chrome extension with manifest v3

"manifest_version":3,"permissions":["contextMenus","storage","activeTab","tabs","scripting","webRequest"],

var posLeft = ( window.width - winWidth ) / 2 ;

解决方法

ManifestV3 扩展使用服务工作者,因此它没有 DOM 或 window。希望可以实现替代 API,请点击 https://crbug.com/1180610 中的星标。

作为一种解决方法,您可以打开一个最小化的窗口,在那里读取屏幕大小,然后调整大小。

  1. 扩展页面

    后台服务工作者:

    chrome.windows.create({url: 'hello.html',state: 'minimized'});
    

    hello.html:

    <head>
      <script src=hello.js></script>
    

    hello.js:

    resizeWindow(chrome.windows.WINDOW_ID_CURRENT,500,300);
    function resizeWindow(id,w,h) {
      chrome.windows.update(id,{
        left: (screen.availWidth - w) / 2,top: (screen.availHeight - h) / 2,width: w,height: h,state: 'normal',});
    }
    
  2. 网页

    manifest.json:

    {
      "content_scripts": [{
        "matches": ["*://*.your.web.url/*"],"js": ["content.js"],"run_at": "document_start"
      }],

    content.js:

    chrome.runtime.sendMessage({
      type: 'screenSize',w: screen.availWidth,h: screen.availHeight,});
    document.addEventListener('DOMContentLoaded',() => {
      // process the page here
    },{once: true});
    

    后台服务工作者:

    chrome.windows.create({url: 'https://your.web.url',state: 'minimized'},wnd => {
      chrome.runtime.onMessage.addListener(function onMessage(msg,sender) {
        if (msg.type === 'screenSize' && sender.tab?.id === wnd.tabs[0].id) {
          chrome.runtime.onMessage.removeListener(onMessage);
          const width = 500,height = 300;
          chrome.windows.update(wnd.id,{
            width,height,left: (msg.w - width) / 2,top: (msg.h - height) / 2,});
        }
      })
    });
    

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。