javascript 删除页面元素的 Chrome 应用程序/扩展程序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28046084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 08:19:39  来源:igfitidea点击:

Chrome App/extension to remove a page element?

javascriptgoogle-chrome-extension

提问by Chris S

I need to create a Chrome Extension to manipulate the HTML on some pages.

我需要创建一个 Chrome 扩展来操作某些页面上的 HTML。

Basically, what I need to do is to remove a <div class="feedmain">inside a page. I'm currently able to remove that <div>using the developer tools, but the element is obviously reloaded when I reload the page, so I would like to develop some extension that does this for me automatically.

基本上,我需要做的是删除<div class="feedmain">页面内的一个。我目前可以<div>使用开发人员工具删除它,但是当我重新加载页面时该元素显然会重新加载,因此我想开发一些自动为我执行此操作的扩展。

So I would like to know if it is possible, and an overview of how it can be done in an extension.

所以我想知道它是否可能,以及如何在扩展中完成它的概述。

回答by Marco Bonelli

Yes, absolutely, that's possible and pretty easy to do: all you need is a content script that will be injected into that particular page to remove the element for you.

是的,绝对可以,而且很容易做到:您所需要的只是一个内容脚本,它将被注入到该特定页面中,以便为您删除元素。

To do what you want you'll need to:

要做你想做的事,你需要:

  1. Create a simple empty Chrome Extension (see herefor the official guide) with a manifest.jsonfile.
  2. Specify the "content_scripts"field in the manifest.json, and declare the script you want to inject. Something like this:

    "content_scripts": [
        {
            "matches": ["http://somesite.com/somepage.html"],
            "js": ["/content_script.js"]
        }
    ]
    

    Take a look hereto find out how content scripts work.

  3. Create a content_script.js, which will delete the element for you. This script will basically only contain the following two lines:

    var element = document.querySelector('div.feedmain');
    element.parentElement.removeChild(element);
    
  1. 使用文件创建一个简单的空 Chrome 扩展程序(请参阅此处获取官方指南)manifest.json
  2. 在 中指定"content_scripts"字段manifest.json,并声明要注入的脚本。像这样的东西:

    "content_scripts": [
        {
            "matches": ["http://somesite.com/somepage.html"],
            "js": ["/content_script.js"]
        }
    ]
    

    查看此处以了解内容脚本的工作原理。

  3. 创建一个content_script.js,它将为您删除元素。这个脚本基本上只包含以下两行:

    var element = document.querySelector('div.feedmain');
    element.parentElement.removeChild(element);