Adding @font-face stylesheet rules to chrome extension

↘锁芯ラ 提交于 2019-12-03 09:35:12

问题


What is the recommended way to add a @font-face stylesheet rule through a chrome-extension? The problem is that the url of the font embed is located from within the extension, so I must do it in javascript in order to use chrome.extension.getURL.

I have tried document.styleSheets[0].addRule through a content-script, but that did not work. To clarify, I also have the font listed under web_accessible_resources.


回答1:


Inject a <style> node, in your content-script. Something like so:

var styleNode           = document.createElement ("style");
styleNode.type          = "text/css";
styleNode.textContent   = "@font-face { font-family: YOUR_FONT; src: url('"
                        + chrome.extension.getURL ("YOUR_FONT.otf")
                        + "'); }"
                        ;
document.head.appendChild (styleNode);



回答2:


You can also specify any additional stuff your extension uses in manifest.json in web_accesible_resources section. Docs are here.

Add this into your manifest.json file:

 "web_accessible_resources": [
    "fonts/*.*",
    "templates/*.html"
 ]

And also correct urls in your css:

@font-face {
  font-family: 'MyFont';
  src: url('chrome-extension://__MSG_@@extension_id__/fonts/font.eot') /* ... */;
}


来源:https://stackoverflow.com/questions/12015074/adding-font-face-stylesheet-rules-to-chrome-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!