How to get my extension's id from JavaScript?

后端 未结 3 1441
滥情空心
滥情空心 2020-12-23 09:32

I\'m writing a Chrome extension, I need to get my extension\'s id in my code, so I don\'t need to change it manually every time. How can I do this?

相关标签:
3条回答
  • 2020-12-23 09:55

    In WebExtensions, you have two options:

    1. chrome.runtime.id
    2. chrome.i18n.getMessage("@@extension_id")

    In Chrome and Opera, they will return the same value, but in Firefox there is a difference.

    In Firefox, chrome.runtime.id will return the so called "Extension ID", but chrome.i18n.getMessage("@@extension_id") will return the "Internal UUID". The extension ID is the same for all users, but the internal UUID is created when the extension is installed and is unique per user.

    Depending on the context, the extension ID will not be what you want. For example, Firefox uses the internal UUID to fill the origin header, not the extension ID.

    Example 1: Ghostery in Firefox 61

    chrome.runtime.id                        --> "firefox@ghostery.com"
    chrome.i18n.getMessage("@@extension_id") --> "e3225586-81a0-47c3-8612-d95fb0c2a609"
    

    For fetch requests from within the extension, Firefox will add the header

    origin: moz-extension://e3225586-81a0-47c3-8612-d95fb0c2a609
    

    Example 2: Ghostery in Chrome

    chrome.runtime.id                        --> "mlomiejdfkolichcflejclcbmpeaniij"
    chrome.i18n.getMessage("@@extension_id") --> "mlomiejdfkolichcflejclcbmpeaniij" 
    

    For fetch requests from within the extension, Chrome will add the header

    origin: chrome-extension://mlomiejdfkolichcflejclcbmpeaniij
    
    0 讨论(0)
  • 2020-12-23 10:01

    If you're doing stuff with localization, it looks like the extension mechanics offer some placeholders for accessing your extension ID:

    If you're just trying to access URLs for local files to your extension, you can just use chrome.extension.getURL("some file name");

    If you have another reason for actually needing to know the id of the extension, I'm not sure there is a straight forward way of getting it from within the extension itself. The two ways that come to me off the top of my head are using chrome.extension.getURL("some file name") and then parsing out the extension id from that returned URL - or using chrome.management.getAll() and looping through all the installed extensions until you find yours using a match on name and then accessing the id:

    0 讨论(0)
  • 2020-12-23 10:03

    You can get it like this (no extra permissions required) in two different ways:

    1. Using runtime api: var myid = chrome.runtime.id;

    2. Using i18n api: var myid = chrome.i18n.getMessage("@@extension_id");

    but you don't need it for opening pages, as chrome.tabs.create() (and some others) understand relative paths.

    So to open index.html from your extension folder you should just use:

    chrome.tabs.create({url: "index.html"});
    
    0 讨论(0)
提交回复
热议问题