为什么Chrome扩展程序图像在添加到DOM时显示为损坏? [英] Why do Chrome Extension Images Show Up As Broken When Added to the DOM?

查看:117
本文介绍了为什么Chrome扩展程序图像在添加到DOM时显示为损坏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建Chrome扩展程序,并试图通过内容脚本将带有背景图片的div添加到DOM。正确加载CSS,图像URL似乎是正确的,通过开发工具检查器查看。

I'm building a Chrome extension, and am trying to add a div with a background image to the DOM via a content script. The CSS loads in correctly, and the image URL seems to be correct looking at it via the Developer Tools inspector.

$('.close-button').css('background', 'url('+chrome.extension.getURL('img/btn_close.png')+')');

URL在检查器中显示为

The URL shows up in the inspector as

chrome-extension://fdghianmcdbcgihapgdbjkdoaaocmoco/img/btn_close.png

但图像不会在后台加载。如果我做同样的事情,但加载图像作为img标签的src,图像在浏览器中明显显示为破碎。

But the image does not load in the background. If I do the same thing, but load the image as the src of an img tag, the image plainly shows as broken in the browser.

但是,当我粘贴URL到浏览器URL栏并加载它,它显示正常。有什么问题加载到DOM?

However, when I paste this URL into the browser URL bar and load it, it shows up fine. What's the problem loading it into the DOM?

推荐答案

我在Chrome扩展文档中找到了答案。默认情况下,扩展根中的文件不能在网页DOM中访问。开发人员可以使用manifest.json文件中的web_accessible_resources设置覆盖此设置:

I found the answer in the chrome extension docs. By default, files in the extension root are not accessible in the web page DOM. The developer can override this with the "web_accessible_resources" setting in the manifest.json file:

http://code.google.com/chrome/extensions/manifest.html#web_accessible_resources

{
  ...
  "web_accessible_resources": [
    "images/my-awesome-image1.png",
    "images/my-amazing-icon1.png",
    "style/double-rainbow.css",
    "script/double-rainbow.js"
  ],
  ...
}

特别留言Matt Greer的评论建议使用数据网址,我相信也可以。

Special shout-out as well to Matt Greer's comment suggesting using a data url, which I believe also works.

这篇关于为什么Chrome扩展程序图像在添加到DOM时显示为损坏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆