【问题标题】:Replacing the Google logo with a Chrome extension用 Chrome 扩展程序替换 Google 徽标
【发布时间】:2021-03-21 04:55:29
【问题描述】:

所以我做了一个扩展,它应该用另一张图片替换搜索结果页面的 Google 徽标。由于徽标的 img 标签没有自己的类或 id,因此我不得不通过将最近的父 div 的 innerHTML 更改为类来做这件事。

ma​​nifest.json:

{
    "name": "Logo Replacer",
    "version": "1.0",
    "manifest_version": 2,
    "web_accessible_resources" : [
        "images/*.png"
    ],
    "description": "Replaces Google logo",
    "permissions": ["activeTab", "declarativeContent", "storage"],

    "content_scripts" : [
        {
            "matches" : [
                "<all_urls>" //normally I want only google.com here but idk how
            ],
            "js": ["changePicture.js"]
        }
    ]
}

changePicture.js:

var googleLogo = document.getElementsByClassName("doodle"); //the parent div has the classes "logo" and "doodle"

googleLogo.innerHTML = "<a href=\"https://www.google.com\" data-hveid=\"8\"><img alt=\"Alt\" height=\"33\" src=\"https://example.com/logo.png\" title=\"Title\" width=\"92\" border=\"0\" data-atf=\"1\"></a>";

【问题讨论】:

  • 那么你到底想做什么?您有任何错误/问题吗?
  • @PraneetDixit 没有错误,我的问题是它什么也没做。我将它导入 Chrome 并没有任何反应。它应该更改页面左上角的 Google 徽标,例如 google.com/search?q=google

标签: javascript json google-chrome google-chrome-extension


【解决方案1】:

document.getElementsByClassName() 返回一个html collection object。要使用此类选择特定的第一个元素,您必须像这样指定索引 -

var googleLogo = document.getElementsByClassName("doodle")[0];

您还可以使用querySelector 简化您的方法以获取特定的img,然后更改src,如下所示 -

document.querySelector(".logo.doodle a img").src = "Your desired source"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多