Google Chrome extension relative path

后端 未结 3 1893
执念已碎
执念已碎 2021-01-30 18:05

I\'m developing a google chrome extension and I\'m running into a relative path problem. If I give a relative path to an image and open the plugin in a certain page it will look

相关标签:
3条回答
  • 2021-01-30 18:17

    @mohamed's answer worked for me but it took my a while to put it all together. I've answered this else where but here is the solution that worked for me.

    My solution.

    With Menifest v2 you need to add web_accessible_resources to the file and then use chrome-extension://__MSG_@@extension_id__/images/pattern.png as the url in your css file.

    CSS:

     #selector {
          background: #fff url('chrome-extension://__MSG_@@extension_id__/images/pattern.png'); 
     }
    

    Manifest.json

    {
      "manifest_version": 2,
    
      "name": "My Extension Name",
      "description": "My Description",
      "version": "1.0",
    
      "content_scripts": [
          {
            "matches": ["https://mydomain.com/*"],
            "css": ["style.css"]
          }
        ],
    
      "permissions": [
        "https://mydomain.com/"
      ],
      "browser_action": {
          "default_icon": {                    
                "19": "images/icon19.png",           
                "38": "images/icon38.png"          
           },
           "default_title": "My Extension Name"  
       },
       "web_accessible_resources": [
           "images/pattern.png"
         ]
    }
    

    p.s. Your manifest.json might look different to this one.

    0 讨论(0)
  • 2021-01-30 18:26

    In some cases you might even use inline base64 encoding of the image. For example,

    <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB..." />
    

    Same you can apply to your CSS. You can find image encoders all over the web.

    0 讨论(0)
  • 2021-01-30 18:35

    If you're using CSS in your extension pages (background, popup, infobar, etc) then you can use relative paths with a slash (/):

    background-image:url("/sprites.png");
    

    The above should work, everyone uses it. But, if your using it for content scripts and you can do the same for any css, you would need to use the predefined message like:

    background-image:url('chrome-extension://__MSG_@@extension_id__/sprites.png');
    

    If you want to programmatically set it, you can use the chrome.extension.getURL syntax as following:

    var url = chrome.extension.getURL('sprites.png');
    

    These are the ways that you can refer to a specific url/image.

    In addition, as mentioned in this answer, if you place your image assets in a directory, these files are not accessible in the web page DOM automatically. The developer should specify the resources that can be loaded the page by using the "web_accessible_resources" setting in the manifest.json file:

    0 讨论(0)
提交回复
热议问题