Search code examples
javascriptgoogle-chrome-extension

How can I detect the browser screensize from inside extension popup


I am working on an extension. The extension is using popup.html and popup.js.

My manifest loads the following permissions:

"permissions": [
  "activeTab",
  "tabs",
  "storage"
] 

I am not currently using any background scripts.

I am trying to detect the browser screen size on load and on resize. I have tried using

window.addEventListener('resize', function(e) window.innerWidth and window.outerWidth

I have tried several other methods as well but no matter what I try the values returned are the height and width of the popup, not the entire browser window. Because of this browser resize is also not detected because the actual popup is not resized with the browser.

Final note: I am using pure js not jquery, so jquery solutions won't help me.

How can I get height/width of browser from inside popup.html?


Solution

  • The popup is a separate window not related to the web page so window refers to the popup's window.

    Use chrome.windows.getCurrent API in the popup script:

    chrome.windows.getCurrent(wnd => {
      console.log(wnd);
    });
    

    The returned object is not a JS window, but a different type from chrome API, see the documentation linked above for more info. And as usual the callback is asynchronous so the value should be used inside.

    Also note that since the popup is a separate window, console.log will print in the popup's devtools: right-click inside the popup and select "inspect" in the menu. In Firefox it's slightly more complicated.