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

后端 未结 3 1516
盖世英雄少女心
盖世英雄少女心 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: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.

提交回复
热议问题