Google Chrome 扩展 - 无法使用 CSS 加载本地图像

发布于 2024-09-16 00:09:06 字数 279 浏览 3 评论 0原文

我有一个简单的 Chrome 扩展程序,它使用内容脚本功能来修改网站。更具体地说,是所述网站的背景图像

由于某种原因,我似乎无法使用本地图像,即使它们包含在扩展中。

body {
    background: #000 url('image.jpg') !important;
    background-repeat: repeat !important;
}

就是这样,最简单的 CSS...但是它行不通。浏览器不加载图像。

I have a simple Chrome extension that uses the content script feature to modify a website. More specifically, the background-image of said website.

For some reason I can't seem to be able to use local images, even though they are packed in the extension.

body {
    background: #000 url('image.jpg') !important;
    background-repeat: repeat !important;
}

That's it, the simplest CSS... but it won't work. The browser doesn't load the image.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

想你的星星会说话 2024-09-23 00:09:06

Chrome 具有i18n 支持,可以在 CSS 中引用您的扩展程序。我将图像保存在扩展程序的图像文件夹中,因此在 CSS 中引用资源,如下所示:

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

图像必须列在 web_accessible_resources 在manifest.json中。

Chrome has i18n support that provides the ability to reference your extension in your CSS. I keep my images in an image folder in the extension, so reference assets in the CSS like so:

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

The image(s) must be listed in web_accessible_resources in manifest.json.

谜泪 2024-09-23 00:09:06

您的图像 URL 应类似于 chrome-extension:///image.jpg

您最好通过 javascript 替换 css。来自文档

//Code for displaying <extensionDir>/images/myimage.png:
var imgURL = chrome.extension.getURL("images/myimage.png");
document.getElementById("someImage").src = imgURL;

Your image URL should look like chrome-extension://<EXTENSION_ID>/image.jpg

You would be better off replacing css through javascript. From docs:

//Code for displaying <extensionDir>/images/myimage.png:
var imgURL = chrome.extension.getURL("images/myimage.png");
document.getElementById("someImage").src = imgURL;
み青杉依旧 2024-09-23 00:09:06

这个问题有很多较旧的答案和解决方案。

截至 2015 年 8 月(使用 Chrome 45 和 Manifest 版本 2),当前链接到 Chrome扩展是以下方法。

1) 使用扩展程序图像的相对路径链接到 CSS 中的资源文件夹:

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

2) 将单个资源添加到扩展程序 web_accessible_resources 部分manifest.json 文件:

"web_accessible_resources": [
  "images/file.png"
]

注意:此方法适用于少数文件,但不能很好地适应许多文件。

相反,更好的方法是利用 Chrome 对 匹配模式将给定目录中的所有文件列入白名单:

{
    "name": "Example Chrome Extension",
    "version": "0.1",
    "manifest_version": 2,
    ...    
    "web_accessible_resources": [
      "images/*"
    ]
}

使用此方法将允许您快速、轻松地使用图像使用本机支持的方法在 Chrome 扩展程序的 CSS 文件中。

There are a lot of older answers and solutions to this question.

As of August 2015 (using Chrome 45 and Manifest version 2), the current "best practice" for linking to local images within Chrome Extensions is the following approach.

1) Link to the asset in your CSS using a relative path to your extension's images folder:

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

2) Add the individual asset to to the web_accessible_resources section of your extension's manifest.json file:

"web_accessible_resources": [
  "images/file.png"
]

Note: This method is suitable for a few files, but doesn't scale well with many files.

Instead, a better method is to leverage Chrome's support for match patterns to whitelist all files within a given directory:

{
    "name": "Example Chrome Extension",
    "version": "0.1",
    "manifest_version": 2,
    ...    
    "web_accessible_resources": [
      "images/*"
    ]
}

Using this approach will allow you to quickly and effortlessly use images in your Chrome Extension's CSS file using natively supported methods.

作死小能手 2024-09-23 00:09:06

一种选择是将图像转换为base64:

然后将数据直接进入你的CSS,例如:

body { background-image: url(data:image/png;base64,iVB...); }

虽然这个 可能不是您在定期开发网页时想要使用的方法,但由于构建 Chrome 扩展程序的一些限制,这是一个很好的选择。

One option would be to convert your image to base64:

and then put the data right into your css like:

body { background-image: url(data:image/png;base64,iVB...); }

While this might not be an approach you would want to use when regularly developing a webpage, it is a great option due to some of the constraints of building a Chrome Extension.

貪欢 2024-09-23 00:09:06

我的解决方案。

使用 Menifest v2,您需要将 web_accessible_resources 添加到文件中,然后使用 chrome-extension://__MSG_@@extension_id__/images/pattern.png 作为 css 中的 url文件。

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"
     ]
}

ps 您的manifest.json 可能与此不同。

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.

揪着可爱 2024-09-23 00:09:06

此CSS版本仅适用于扩展环境(应用程序页面、弹出页面、背景页面、选项页面)以及content_scripts CSS文件。

在.less文件中,我始终在开头设置一个变量:

@extensionId : ~"__MSG_@@extension_id__";

然后,如果您想像图像一样引用扩展本地资源,请使用:

.close{
    background-image: url("chrome-extension://@{extensionId}/images/close.png");
}

This CSS-version-only works in extension environment (app page, popup page, background page, option page) as well as content_scripts CSS file.

In .less file, I always set a variable at the beginning:

@extensionId : ~"__MSG_@@extension_id__";

Then later, if you want to refer to extension-local-resource like images, use:

.close{
    background-image: url("chrome-extension://@{extensionId}/images/close.png");
}
〃安静 2024-09-23 00:09:06

值得一提的是,在 web_accessible_resources 中您可以使用通配符。 代替

“images/pattern.png ”

因此,您可以使用

“images/*”

One thing to mention is that in the web_accessible_resources you can use wildcards. So instead of

"images/pattern.png"

You can use

"images/*"

醉生梦死 2024-09-23 00:09:06

只是为了澄清,根据 文档,扩展中的每个文件也是可通过绝对 URL 访问,如下所示:

chrome-extension:///

请注意 < ExtensionID> 是扩展系统为每个扩展生成的唯一标识符。您可以通过访问 URL chrome://extensions 查看所有已加载扩展程序的 ID。 是扩展程序顶部文件夹下的文件位置;它与相对 URL 相同。

...

更改 CSS 中的背景图像:

#id { 背景图像:
url("chrome-extension:///"); }

通过 JavaScript 更改 CSS 中的背景图像:

document.getElementById('id').style.backgroundImage =
“url('chrome-extension:///')”);

通过 jQuery 更改 CSS 中的背景图像:

$("#id").css("背景图像",
“url('chrome-extension:///')”);

Just to clarify, according to the documentation, every file in an extension is also accessible by an absolute URL like this:

chrome-extension://<extensionID>/<pathToFile>

Note the <extensionID> is a unique identifier that the extension system generates for each extension. You can see the IDs for all your loaded extensions by going to the URL chrome://extensions. The <pathToFile> is the location of the file under the extension's top folder; it's the same as the relative URL.

...

Changing background image in CSS:

#id { background-image:
url("chrome-extension://<extensionID>/<pathToFile>"); }

Changing background image in CSS through JavaScript:

document.getElementById('id').style.backgroundImage =
"url('chrome-extension://<extensionID>/<pathToFile>')");

Changing background image in CSS through jQuery:

$("#id").css("background-image",
"url('chrome-extension://<extensionID>/<pathToFile>')");

梦屿孤独相伴 2024-09-23 00:09:06

我们可以使用 Chrome 扩展程序的预定义消息。
预定义消息

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

we can use the Predefined messages of Chrome extensions.
Predefined messages

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

瘫痪情歌 2024-09-23 00:09:06

对于清单 v3,有一些修改:

  1. chrome.extension.getUrl() -> chrome.runtime.getUrl()
  2. “web_accessible_resources”-> “web_accessible_resources.resources”
  3. 填写“web_accessible_resources.matches”

2、3,如下所示:

"web_accessible_resources": [{
  "resources": ["images/logo.png"],
  "matches": ["<all_urls>"],
}],

参考:

For manifest v3, there are some modifications:

  1. chrome.extension.getUrl() -> chrome.runtime.getUrl()
  2. "web_accessible_resources" -> "web_accessible_resources.resources"
  3. fill in "web_accessible_resources.matches"

2, 3 like this:

"web_accessible_resources": [{
  "resources": ["images/logo.png"],
  "matches": ["<all_urls>"],
}],

reference:

黑寡妇 2024-09-23 00:09:06

上面的答案很好,但是您的扩展程序每次安装时都会获得一个新的 id,因此如果您要在某个时候将其公开,则手动输入 id 是行不通的。

这是我使用清单 v.3 的解决方案:

//Get the url from some file within your extension's folder and store it on a global variable
var url = chrome.runtime.getURL('my_extension/img/Icon.svg');

//Take off the last part from the url string
url = url.replace('img/Icon.svg', '');

现在将每个 img 标签上的 src 属性替换为自定义属性,并保留文件路径的值,如下所示:

<img ref-file="img/IconStop.svg" alt="">

然后在加载 html 后运行此函数:

loadImgs = function () {
    $("img[ref-file]").each(function() {
        var ref_file = $(this).attr('ref-file');
        url = url + ref_file;
        $(this).attr('src', url);
    });
}

Those answers above are great but your extension gets a new id every time it gets installed, so putting the id manually doesn't work if you gonna make it public at some point.

Here's my solution using manifest v.3:

//Get the url from some file within your extension's folder and store it on a global variable
var url = chrome.runtime.getURL('my_extension/img/Icon.svg');

//Take off the last part from the url string
url = url.replace('img/Icon.svg', '');

Now replace the src attribute for a custom one on every img tag and keep the file path as it's value like this:

<img ref-file="img/IconStop.svg" alt="">

Then run this function after loading the html:

loadImgs = function () {
    $("img[ref-file]").each(function() {
        var ref_file = $(this).attr('ref-file');
        url = url + ref_file;
        $(this).attr('src', url);
    });
}
彩扇题诗 2024-09-23 00:09:06

这在 Vue.js 内置的 Chrome 扩展中对我有用
徽标存储在 /public/images/logo.png 中,我的组件存储在 /src/components/shared/logo.vue

<template>
  <img :src="logoURL" alt="Logo" />
</template>
<script>
export default {
    computed: {
        logoURL() {
            return chrome.runtime.getURL("images/logo.png");
        }
    }
}
</script>

ma​​nifest.json 中>

{
  "manifest_version": 3
}

This works for me in a Chrome extension built in Vue.js
The logo was stored in /public/images/logo.png and my components in /src/components/shared/logo.vue

<template>
  <img :src="logoURL" alt="Logo" />
</template>
<script>
export default {
    computed: {
        logoURL() {
            return chrome.runtime.getURL("images/logo.png");
        }
    }
}
</script>

manifest.json

{
  "manifest_version": 3
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文