How can I know if browser is Chrome vs Firefox from web extension popup JavaScript?

后端 未结 3 1517
盖世英雄少女心
盖世英雄少女心 2021-01-25 06:05

I am using the chrome namespace for both Chrome and Firefox, but would like to know which browser is running the web extension.

相关标签:
3条回答
  • 2021-01-25 06:45
    • Check chrome.app which is absent in Firefox:

      const isFirefox = !chrome.app;
      
    • Check for browser which is absent in Chrome:

      const isFirefox = window.browser && browser.runtime;
      

      (the additional check is to avoid false positives on pages that have an element with id="browser" that creates a named property on window object for this element)

    • Use the asynchronous browser.runtime.getBrowserInfo.

    P.S. navigator.userAgent may be changed during debugging in devtools when switching to device mode or via about:config option in Firefox so it's an unreliable source.

    0 讨论(0)
  • 2021-01-25 06:50

    This is what I do in my own extensions to check for Firefox (FF) vs Chrome:

    const FF = typeof browser !== 'undefined';
    

    Update: (1)
    Here is an explanation .....

    I am using the chrome namespace for both Chrome and Firefox, but would like to know which browser is running the web extension.

    AFA I understand, the question relates to extension code and not content code. I use above code in background script in "firefox-webextensions" or "google-chrome-extension" background script.

    From then on then code would be:

    if (FF) {...}
    else { .... }
    

    Once established, content script has no bearing on it.

    In case of a developer who somehow decides to use id="browser" then a further step could be added which returns a boolean true|false e.g.

    const FF = typeof browser !== 'undefined' && !!browser.runtime;
    

    Worth nothing that the following returns an object or undefined and not a boolean

    const isFirefox = window.browser && browser.runtime;
    

    While it works fine in if() conditionals, it wont work in other situations where a boolean would be required (e.g. switch)

    (1) Note: Marking down answers, discourages people from spending time and effort in answering questions in future.

    0 讨论(0)
  • 2021-01-25 06:52

    Links to extension resources have different schemes in Chrome and Firefox.

    const isFirefox = chrome.runtime.getURL('').startsWith('moz-extension://');
    const isChrome = chrome.runtime.getURL('').startsWith('chrome-extension://');
    
    0 讨论(0)
提交回复
热议问题