代码之家  ›  专栏  ›  技术社区  ›  senox13

如何从JavaScript中引用作为Chrome扩展的一部分的文件

  •  0
  • senox13  · 技术社区  · 7 年前

    我有一个Google Chrome扩展,它只包含一个JavaScript文件,可以加载特定域中的页面。该脚本非常简单,它只是从特定元素读取innerHTML,然后根据元素所包含的内容更改页面标题。代码如下。

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

    这部分工作正常,我想对其进行修改,以便它也可以更改页面的图标。由于这个脚本运行的页面从一开始就没有在标题中链接图标,所以我所要做的就是添加它并设置它的相关属性。已实现此脚本的新版本:

    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);
    

    虽然这确实成功添加了链接标签,但图标显示为未找到,因为chrome在/图标中查找它。png。我也试过了 ./icon.png ,但结果是一样的。访问作为chrome扩展名一部分的文件的正确方法是什么?

    感谢您抽出时间。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Florian Hecht    7 年前

    可以使用Base64注入图标。

    <link href="data:image/x-icon;base64,AAABAAEAEB8AAA==" rel="icon" type="image/x-icon" />
    

    或者您可以尝试在清单中使用Web Accessible ressource。 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/*"
      ],
      ...
    }