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

时间:2021-06-30 11:43:04

标签: google-chrome-extension google-chrome-devtools chrome-extension-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 ;

1 个答案:

答案 0 :(得分:0)

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,
            state: 'normal',
          });
        }
      })
    });