[英]How to reference a file that is part of a Chrome extension from within JavaScript
I have a Google Chrome extension that contains only a single JavaScript file, which gets loaded for pages in a certain domain. 我有一个Google Chrome扩展程序,它仅包含一个JavaScript文件,该文件会为特定域中的页面加载。 The script is very simple, it just reads the innerHTML from a particular element, then changes the title of the page depending on what the element contained.
该脚本非常简单,它只是从特定元素中读取innerHTML,然后根据元素所包含的内容更改页面标题。 Code below.
下面的代码。
var status = document.getElementById("target-element").innerHTML.toLowerCase();
if(status.indexOf("string1") != -1){ //Using String.indexOf() to check for substring
document.title = "Title A";
}if(status.indexOf("string2") != -1){
document.title = "Title B";
}else{ //Running
document.title = "Title C";
}
This part works fine, and I wanted to modify it so that it could also change a page's icon as well. 这部分工作正常,我想对其进行修改,以便它也可以更改页面的图标。 As the pages this script runs on don't ever have an icon linked in their header to begin with, all I have to do is add it and set it's relevant attributes.
由于此脚本运行的页面的开头没有链接图标,因此我要做的就是添加它并设置它的相关属性。 New version of the script with this implemented:
已实现的脚本的新版本:
var status = document.getElementById("target-element").innerHTML.toLowerCase();
var iconLink = document.createElement('link');
iconLink.rel = "icon";
if(status.indexOf("string1") != -1){
document.title = "Title A";
iconLink.href = "icona.png";
}if(status.indexOf("string2") != -1){
document.title = "Title B";
iconLink.href = "iconb.png";
}else{
document.title = "Title C";
iconLink.href = "iconc.png";
}
document.head.appendChild(iconLink);
While this does successfully add the link tag, the icon comes up as not found because chrome looks for it in /icon.png. 尽管此操作确实成功添加了链接标记,但图标未显示出来,因为chrome在/icon.png中寻找它。 I also tried
./icon.png
, but the result was the same. 我也尝试过
./icon.png
,但是结果是一样的。 What is the correct way to access a file that is part of a chrome extension? 访问chrome扩展名一部分的文件的正确方法是什么?
Thank you for your time. 感谢您的时间。
You can use Base64 to inject your icon. 您可以使用Base64注入图标。
<link href="data:image/x-icon;base64,AAABAAEAEB8AAA==" rel="icon" type="image/x-icon" />
Or you can try to use Web Accessibile ressource in your manifest. 或者,您可以尝试在清单中使用Web Accessibile资源。 https://developer.chrome.com/extensions/manifest/web_accessible_resources
https://developer.chrome.com/extensions/manifest/web_accessible_resources
{
...
"web_accessible_resources": [
"images/*.png",
"style/double-rainbow.css",
"script/double-rainbow.js",
"script/main.js",
"templates/*"
],
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.